Getter inside setter in Swift 3

I use 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 this is the right way to call getter inside setter? I mean:

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

Should I use self instead of /*HOW TO CALL GETTER HERE? */ /*HOW TO CALL GETTER HERE? */ , this will not work.

+6
source share
2 answers

You can just call the value in your 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) } } 
+9
source

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

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

The name newValue in the setter definition represents the value that applies.

You can drop the following on the 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 getter in your setter definition, you could. Perhaps you would like to apply only newValue in the installer based on some getter condition:

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

It is also relevant and should meet your requirements.

+1
source

Source: https://habr.com/ru/post/1014695/


All Articles