简体   繁体   中英

Getters and Setters in Swift

Why do we need to use setters in the particular case below in Swift.

I'm trying to convert 'display.text' String to Double . I understand that getter brings back String value and converts it to Double and assigns this value to variable newValue .

Question: why we set display.text value back into String again using = "\\(newValue)" if we just converted it into Double ?

var doubleValue: Double {
    get {
        return NSNumberFormatter().numberFromString(display.text!)!.doubleValue
    }
    set {
        display.text = "\(newValue)"
    }
}

I understand that getter brings back String value and converts it to Double and assigns this value to variable newValue.

This isn't correct. The getter just returns the double. There is no newValue in the getter.

In the setter, newValue is a shortcut for "the implied argument of the setter." The explicit syntax is this:

var doubleValue: Double {
    ...
    set(newValue) {
        display.text = "\(newValue)"
    }
}

In order to override setter and getter for swift variables use the below given code

var temX : Int? 
var x: Int?{

set(newX){

   temX = newX

}

get{

    return temX

}

We need to keep the value of variable in a temporary variable, since trying to access the same variable whose getter/setter is being overridden will result in infinite loops.

We can invoke the setter simply like this

x = 10

Getter will be invoked on firing below given line of code

var newVar = x

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM