Karen  Karapetyan
Karen Karapetyan

Reputation: 754

Swift 3 getter method

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

Answers (2)

gnasher729
gnasher729

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

vadian
vadian

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

Related Questions