John Difool
John Difool

Reputation: 5732

Idiomatic Swift: Getter & Setter boiler plate coding

While migrating some projects from Objective-C to Swift, I find myself replacing the @property/@synthesize syntax with a lot more boiler-plate code.

For example, for every @property I am implementing, I currently use this pattern:

var foo: Foo? {
    get {
        return _foo
    }
    set {
        _foo = newValue
    }
}

var _foo: Foo?

It ends up adding quickly. Compare this with the 2 lines in Objective-C. That doesn't feel right.

Should I just replace the code using _foo in my ported classes with foo and skip the abstraction of each public var behind an interface entirely?

Upvotes: 0

Views: 201

Answers (1)

Marcus Rossel
Marcus Rossel

Reputation: 3268

As @Amit89 pointed out, you can simply use _foo.
In your example, adding foo does exactly nothing, as you simply recreated the get and set functionality already supplied with _foo.

If you want to control how _foo is set you can use property observers:

var _foo: Foo? {
    didSet { }
    willSet { }
}

If you want to control how _foo is retrieved, then it would indeed make sense to create a private version of _foo, and then accessing it via a computed property:

private var _foo: Foo?

var foo: Foo? {
    get { 
        // return `_foo` in some special way
    }

    // add a setter if you want to set `_foo` in some special way
}

Upvotes: 2

Related Questions