Backticks in `Swift`
The backtick ` in Swift can be used in variety of ways. It allows you to create identifiers from language keywords.
One of the most important uses is the interaction with other languages that have different reserved keywords.
From Swift you can call C and Objective-C functions directly, but imagine you want to call C function that is named guard. You cannot call it without a backtick:
`guard`()
Perhaps better showcase would be an enum. You might want to create an enum with following values:
enum Foo {
case `var`
case `let`
case `class`
case `func`
}
let items = [Foo.class, Foo.let, .var]
Using backticks enables you to use reserved language keywords as you see fit.
If you want to replicate Apple's API design in your codebase and use the default keyword as a property name, you'll have to use a backtick. For example NotificationCenter uses singleton called default, but default is also a keyword used in switch statements. To implement your own property with name default, you can use something like this:
class MyOwnNotificationCenter {
static let `default` = MyOwnNotificationCenter()
...
}
Have you ever used [weak self] in a closure? If not, you should! But once you make weak reference to self, self becomes optional and sometimes it can be a pain to work with it. Before Swift 4.2 you had to do something like this to keep strong reference to self and keep it's name (or change the name and use strongSelf variable name):
self.provider.fetchData { [weak self] (fetchedData) in
guard let `self` = self else { return }
let processedData = self.processData(fetchedData)
self.updateUI(with: processedData)
}
But as of Swift 4.2 you can now do something like this:
self.provider.fetchData { [weak self] (fetchedData) in
guard let self = self else { return }
let processedData = self.processData(fetchedData)
self.updateUI(with: processedData)
}
You can now upgrade reference from weak to strong using optional binding and it is now consistent with other optional variables and properties used in your codebase.
Those are just few examples for using backticks, but I think you get the idea. It is really neat that we have a way to name our identifiers how we want, even if they are same as language-reserved keywords.
We all know that naming variables is one of the hardest things in programming 😉.
M.