Last active
January 24, 2020 17:22
-
-
Save PetreVane/a2294758d3a6499b7eec3f18fc96ca4f to your computer and use it in GitHub Desktop.
"Yes, you often need to explicitly declare the type. Yes, you need that = sign. And Yes, you need the parentheses after the closing brace."
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Lazy Closures | |
class Person { | |
let name: String | |
init(name: String) { | |
self.name = name | |
} | |
// Remember to add the closing brace '()' at the end of the closure declaration | |
lazy var reversedName = { | |
return "\(self.name) backwards is: \(String(self.name.reversed()))" | |
}() | |
} | |
let person = Person(name: "SomeName") | |
let reversedName = person.reversedName | |
print(reversedName) | |
/* | |
“Swift is smart enough to realize what’s going on, and no reference cycle will be created. | |
Under the hood, any closure like this – one that is immediately applied – is considered to be “non-escaping”, which in our situation means it won’t be used anywhere else. That is, this closure can’t be stored as a property and called later on. Not only does this automatically ensure self is considered to be unowned, but it also enables the Swift compiler to make some extra optimizations because it has more information about the closure. | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment