Swift:全局变量不更新

时间:2015-01-01 13:47:36

标签: ios xcode button swift observers

在名为Menu的文件中,我有:

class Menu: UIViewController {
var no_of_swipes = 99

@IBAction func pressedThreeSwipes(sender: AnyObject) {
    no_of_swipes = 3
}
}

在另一个文件中我有这个:     课堂游戏:UIView {

func didMoveToView(view: UIView) {
    /* Setup your scene here */

    var swipes = Menu()

    var no_of_swipes: Int = 0 {
        didSet {
            println("\(swipes.no_of_swipes) should be three")
        }
    }
}

然而,当我按下菜单中的按钮时,触发移动到第二个文件的segue。控制台声明no_of_swipes = 0.在//行x中,如果我删除= 0,我收到有关初始化的错误。所以,我的问题是:为什么不是no_of_swipes 3?我认为这是获取no_of_swipes或观察者的问题。

提前谢谢

1 个答案:

答案 0 :(得分:3)

你的问题是你误解了didSet的基本原理。在为属性分配内容时执行此操作。将以下内容粘贴到Playground中。

class Menu {
  var no_of_swipes = 5

  @IBAction func pressedThreeSwipes(sender: AnyObject) {
    no_of_swipes = 3
  }

}

var swipes = Menu()
var no_of_swipes: Int = 0 { //line x
didSet {
  println("i have been changed, and \(swipes.no_of_swipes) is what we do not get")
}
}

no_of_swipes = 99
println(no_of_swipes)
no_of_swipes = swipes.no_of_swipes
println(no_of_swipes)

我希望这是自我解释的。

根据评论修改:

class Menu {
  var no_of_swipes = 5
  var subscriber:((Int)->())?

  @IBAction func pressedThreeSwipes(sender: AnyObject) {
    no_of_swipes = 3
    subscriber?(no_of_swipes) // for convenience pass the number
  }

}

class MyOtherClass {
  var swipes = Menu()
  init() {
      swipes.subscriber = myActionOnSwipe
  }

  func myActionOnSwipe(swipes:Int) {
    println("Swipes is \(swipes)")
  }
}

如果添加以下内容(也在Playground中):

let c1 = MyOtherClass()
c1.swipes.pressedThreeSwipes(c1)

你会看到它是如何运作的。