【问题标题】:How to share a variable between subclasses in Swift 3?如何在 Swift 3 中的子类之间共享变量?
【发布时间】:2016-12-12 15:39:28
【问题描述】:

我有一个超类,它有一个布尔变量,我想在子类之间共享它(通过引用传递它)

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 更改它。

如果有任何帮助,我将不胜感激

【问题讨论】:

  • 这里显示的代码甚至不会编译,所以没有人可以验证你的问题,也不清楚问题是什么,因为这里的代码没有重现它(特别是因为它会永远不要调用myButtonTouched,即使它确实编译了,它不会)。我只能猜测您的意思是 sharedVariable 只是一个变量,而不是每个实例都有一个单独的变量,在这种情况下,您可以将 static 放在其声明前面并访问 parentClass.sharedVariable
  • 您需要展示如何创建这些类的实例,并清楚地说明属性如何更新以及值如何与您的预期不符。

标签: swift inheritance


【解决方案1】:

您可以像这样使用静态变量(我稍微更正了代码和代码样式):

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

【讨论】:

  • 如果你能解释为什么你投反对票会很好,因为这显然回答了这个问题..
  • 我没有否决您的回答。实际上这是我问题的答案。谢谢
  • @Besat 别人做过,我喜欢从我的错误中学习,但没关系;)
  • 我不是对答案投反对票的人,但我认为投反对票与您有点宣传反模式这一事实有关。静态变量不应用于将数据从一个实例传递到另一个实例。
  • @Cristik 我同意你的观点,但就问题的字母而言,答案是正确的,我们不知道被问到的上下文。当您可以使用单例时,有一些半合法的情况,例如数据库连接、应用程序委托等。谁投反对票最好发表评论。
猜你喜欢
  • 1970-01-01
  • 2011-02-09
  • 1970-01-01
  • 1970-01-01
  • 2013-06-10
  • 2021-10-21
  • 1970-01-01
  • 1970-01-01
  • 2021-10-11
相关资源
最近更新 更多