Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there such thing as 'didGet' in Swift? A method that is run whenever a variable is accessed?

Tags:

swift

Basically, I want to do like this:

var counter : Int = 0;
private var _data : String;
var data : String {
    get { counter += 1; return _data; }
    set { _data = newValue; }
}

Then I want to reduce it like this:

var counter : Int = 0;
var data : String {
    get { counter += 1; return data; }
    set { data = newValue; }
}

But I noticed that this can't be done. (Error: Variable used within its initial value). So I then want to simplify it like this:

var counter : Int = 0;
var data : String {
    didGet { counter += 1; }
}

But there's no such thing as didGet. Is there any way to do this without adding new other variable? I need to run counter += 1 every time data is accessed, without adding new variable as storage. Thanks.

like image 283
Chen Li Yong Avatar asked Sep 11 '17 07:09

Chen Li Yong


1 Answers

No, there is no way to do it without adding new variable.

If you return in the get method of the variable the same variable, you will create infinite loop.

like image 79
Vlad Khambir Avatar answered Sep 28 '22 05:09

Vlad Khambir