我有一个父类(super class),它有一个 bool 变量,我想在子类之间共享它(通过引用传递)
Class parentClass: UIViewController {
var sharedVariable: Bool = false
}
Class firstChild: parentClass {
@IBAction func myButtonTouched(_ sender: Any) {
sharedVariable = true
}
}
Class secondChild: parentClass {
print(sharedVariable)
}
但是当我在 firstClass 中更改 sharedVariable 时,它不会为 secondClass 更改它。
如果有任何帮助,我将不胜感激
最佳答案
你可以使用一个静态变量,像这样(我稍微修正了代码和代码风格):
class ParentClass: UIViewController {
static var sharedVariable: Bool = false
}
class FirstChild: ParentClass {
@IBAction func myButtonTouched(_ sender: Any) {
ParentClass.sharedVariable = true
}
}
class SecondChild: ParentClass {
func test() {
print(ParentClass.sharedVariable)
}
}
然后,要进行测试,您可以:
let secondChild = SecondChild()
secondChild.test() // prints false
let firstChild = FirstChild()
firstChild.myButtonTouched(firstChild)
secondChild.test() //prints true
关于swift - 如何在 Swift 3 的子类之间共享变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41104365/