pprevalon pprevalon - 2 months ago 8
Swift Question

How can I use a variable for `didSet` property from outside of of the method

How can I use a variable for

didSet
property from outside of of the method

This work

override func viewWillAppear(_ animated: Bool) {
var myString = "sadf" {
didSet{
print("myString did change from "+oldValue+" to "+myString)
}
}
}


But I want to do this

//add var outside of method
var myString:String!

override func viewWillAppear(_ animated: Bool) {
//call variable inside of method
myString = "sadf" {
didSet{
print("myString did change from "+oldValue+" to "+myString)
}
}
}

Answer

You can define didSet for the property outside of the method. This should work:

var myString:String = "oldString" {
    didSet(oldValue) {
        print("myString did change from "+oldValue+" to "+myString)
    }
}

override func viewWillAppear(_ animated: Bool) {
    myString = "sadf"
    myString = "secondCall"
}

The output will be look like this:

myString did change from  to sadf
myString did change from sadf to secondCall

For more information you should read the chapter about property observers in the apple documentation: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Properties.html

Comments