Skip to content

Instantly share code, notes, and snippets.

@0xtmphey
Created October 16, 2019 07:45
Show Gist options
  • Save 0xtmphey/0ead1b53802f860e281f89205fd1bd58 to your computer and use it in GitHub Desktop.
Save 0xtmphey/0ead1b53802f860e281f89205fd1bd58 to your computer and use it in GitHub Desktop.
@propertyWrapper
struct Lateinit<T> {
private var _value: T?
var wrappedValue: T {
get {
guard let value = _value else {
fatalError("Property being accessed without initialization")
}
return value
}
set {
guard _value == nil else {
fatalError("Property already initialized")
}
_value = newValue
}
}
}
// Now we can declate non-optional variable without initialization
@Lateinit var name: String
// This is going to crash
print(name)
//So, firstly, we need to initialize it
name = "Swift"
print(name)
//Also, we can't change property after initialization
name = "Another one" //This is forbidden and going to crash
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment