Vyacheslav
Vyacheslav

Reputation: 27221

Getter inside setter in Swift 3

I'm using this variable

public var tick: Int64 {
    get {
        return UserDefaults.standard.object(forKey: TICK) as? Int64 ?? 0
    }
    set(v) {
        let cur = UserDefaults.standard.object(forKey: TICK) as? Int64 ?? 0 + v
        UserDefaults.standard.set(cur, forKey: TICK)
    }
}

But I want to know, that is the proper way to call getter in inside setter? I mean:

set(v) {
    let cur = /*HOW TO CALL GETTER HERE? */ + v
    UserDefaults.standard.set(cur, forKey: TICK)
}

if I use self instead of /*HOW TO CALL GETTER HERE? */ , it doesn't work.

Upvotes: 6

Views: 6721

Answers (2)

Michael Fourre
Michael Fourre

Reputation: 3015

A standard implementation of a computed variable with getter and setter is as follows:

private var stored: String

public var computed: String {
    get {
        return stored
    }
    set {
        stored = newValue
    }
}

The name newValue in a setter definition represents the value which is being applied.

You could throw the following into a playground to see:

struct SomeStruct {
    private var stored: String = ""

    public var computed: String {
        get {
            return self.stored
        }
        set {
            self.stored = newValue
        }
    }
}

var value = SomeStruct()
print(value.computed)
value.computed = "new string"
print(value.computed)

If you really wanted to reference the getter in your setter definition, you could. Perhaps you would want to only apply the newValue in the setter based on some kind of condition of the getter:

public var computed: String {
    get {
        return self.stored
    }
    set {
        self.stored = self.computed == "" ? self.computed : newValue
    }
}

This is also valid and should be able to fit your requirements.

Upvotes: 2

FelixSFD
FelixSFD

Reputation: 6102

You can simply call the value (tick) within its setter to get the old value:

public var tick: Int64 {
    get {
        return UserDefaults.standard.object(forKey: TICK) as? Int64 ?? 0
    }
    set(v) {
        let cur = tick + v
        UserDefaults.standard.set(cur, forKey: TICK)
    }
}

Upvotes: 10

Related Questions