Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift language: How to define a computed variable with observer?

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.

like image 637
Just a learner Avatar asked Mar 30 '15 12:03

Just a learner


2 Answers

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!
    }
}
like image 51
Abdullah Avatar answered Nov 09 '22 23:11

Abdullah


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.

like image 41
GoZoner Avatar answered Nov 10 '22 00:11

GoZoner