I'm new with Swift and playing with the language. I've learned the concept of computed variable and variable observer. I want to know if it's possible to define both of them at the same time when I define a variable. I've tried but failed. Below is my code (not working!).
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, is this possible? Thanks.
The short answer, it is not possible.
I think the idea of Computed Properties and Stored Properties are quite exclusive.
Talking about Stored Properties, think of it as member variables with feature to know when they are being set or assigned. They are stored not computed and hence they could be assigned a value and could be set or assigned by other class or methods outside of defining class.
In case of Computed Properties they are computed every time they are accessed and hence are not stored. I feel even the idea of setting is also not in line with Computed Properties because if you set it is not computed.
In case of setter in a property, you know when it is being set or assigned and hence no need of willSet or didSet.
var myProp: String {
set {
//You know it is being set here. :-)
//No need of an event to tell you that!
}
}
It can't be done:
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 }
^
The error messages describes why.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With