如何从方法外部的`didSet`属性使用变量

时间:2016-09-27 19:00:36

标签: swift

如何在方法

之外的didSet属性中使用变量

这项工作

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

但我想这样做

//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)
        }
    }
}

3 个答案:

答案 0 :(得分:2)

您可以为方法外部的属性定义didSet。这应该有效:

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

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

输出将如下所示:

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

有关更多信息,请阅读Apple文档中有关属性观察者的章节:https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Properties.html

答案 1 :(得分:0)

简单地将整个didSet结构移动到伴随myString定义为全局的结构中,就像拥有它一样。没有法律规定didSet仅适用于财产;它可以应用于全局变量,甚至可以应用于局部变量(尽管谁知道你为什么要这样做)!这完全合法:

var myString : String! {
    didSet {
        print("myString changed")
    }
}
override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    myString = "asdf"
}

答案 2 :(得分:0)

您可以做的是,声明另一个lazy var以保留您想要的旧/新值,并将其分配到您的viewWillAppear方法中,如下所示:

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