Quick language: how to determine a computed variable using an observer?

I am new to Swift and play with the language. I learned the concept of a computed variable and an observer variable. I want to know whether it is possible to define both of them at the same time when I define a variable. I tried, but could not. Below is my code (doesn't work!).

var a:Int = 88 { get { println("get...") return 77 } set { a = newValue + 1 } } { willSet { println("In willSet") println("Will set a to \(newValue)") println("Out willSet") } didSet { println("In didSet") println("Old value of a is \(oldValue)") println(a) if(a % 2 != 0) { a++ } println("Out didSet") } } println(a) a = 99 println(a) 

I want to know if this is possible? Thanks.

+5
source share
4 answers

Unable to execute:

 Welcome to Swift version 1.2. Type :help for assistance. 1> class Foo { 2. var bar : Int { 3. get { return 1 } 4. willSet { println ("will") } 5. } 6. } repl.swift:3:9: error: willSet variable may not also have a get specifier get { return 1 } ^ 

Error messages describe why.

+3
source

The short answer is, this is not possible.

I think the idea of ​​computed properties and stored properties is pretty exclusive.

Speaking of stored properties, think of it as member variables with the function to know when they are set or assigned. They are stored non-computable and, therefore, they can be assigned a value and can be set or assigned by another class or methods outside the class definition.

In the case of computed properties, they are computed every time they are accessed and, therefore, are not saved. I feel that even the idea of ​​customization also does not match Computed Properties, because if you install it, it is not calculated.

In the case of setting, in the property you know when it is installed or assigned, and therefore there will be no need to configure willSet or didSet.

 var myProp: String { set { //You know it is being set here. :-) //No need of an event to tell you that! } } 
+6
source

I think that property observers can only apply to stored properties. Computed properties and property observers are similar in the sense that they are both called when the property value changes, and we can even treat calculated properties as property observers

So, I do not think that we can define a computed variable with an observer.

+1
source

For computed properties, observers would not really add much value. It is easy to make an equivalent in a given function like this:

 set { // do willSet logic here let oldValue = a a = newValue + 1 // do didSet logic here } 

If the logic of willSet or didSet is complex, you can reorganize it into member functions such as willSetA or didSetA.

+1
source

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


All Articles