Reputation: 754
I want to write getter and want that the getter return the same object every time when I call. This is my code.
var someObject:NSObject? {
get {
if _someObject == nil {
_someObject = NSObject()
}
return _someObject;
}
}
The compiler gives the error Use of unresolved identifier '_someObject' How do I write the correct getter method in Swift 3?
Upvotes: 0
Views: 476
Reputation: 52538
In Swift, a property named someObject doesn't have a backing variable named _someObject. You can of course declare your own private variable named _someObject. As an advantage, there is no need to declare someObject as an optional, since the getter isn't ever supposed to return nil.
Upvotes: 0
Reputation: 285082
Don't translate Objective-C code literally.
The Swift equivalent is a lazy computed property
lazy var someObject : NSObject = {
return NSObject()
}()
The object is created once when the property is accessed the first time and
you get always a non-optional object.
Upvotes: 2