Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift setter and getter issues [closed]

Tags:

ios

swift

I know there are a few questions regarding with this already. And I know swift can only customise property setter and getter for computed properties. But I think this is the worst part of Swift. Because:

  1. All variables are exposed to outside. There is no private or public properties any more.
  2. There is no way to access the "internal" variable of the property like the objective-c, _variable

My code is like this:

var value : Float = 0.0 {

    willSet {
        setValue(newValue, animated: false)
    }
}

func setValue(newValue:Float, animated:Bool) {

    if(newValue != self.value) {
        // TODO: this will cause problem because I there is no alternative way like Objective-c to access _value
        self.value = ....

        // do whatever I want 
    }
}

The problem is the there is no _value like in Objective-c, the self.value will cause the value's willSet be called again.

Any idea? Thanks

like image 599
Bagusflyer Avatar asked Jul 08 '14 04:07

Bagusflyer


1 Answers

willSet does not define a setter. set does.

var privateValue: Float = 0.0;
var value: Float {
  set(newValue) {
    if newValue != privateValue {
      privateValue = newValue;
      // do whatever I want
    }
  }
  get {
    return privateValue;
  }
}
  1. All variables are exposed to outside. There is no private or public properties any more.
  2. There is no way to access the "internal" variable of the property like the objective-c, _variable

According to my understanding, privateValue will not be accessible anywhere outside the local scope, which would resolve both of your complaints. (EDIT: might be wrong about accessibility; see comments.)

like image 81
Amadan Avatar answered Nov 05 '22 10:11

Amadan