【问题标题】:Swift: Global variable not updatingSwift:全局变量不更新
【发布时间】:2015-01-01 13:47:35
【问题描述】:

在一个名为 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 或观察者的问题。

提前谢谢你

【问题讨论】:

  • 您访问的不是Menu 的同一个实例,而是创建一个新实例。要在不同的视图控制器中访问 Menu 的实例,您可以将其传入。
  • @LyndseyScott 请解释如何做到这一点。
  • 您已经声明了两次no_of_swipes。它们是不同的变量。省略最上面的那个。
  • @ThomasKilian 请您提供更详细的答案。谢谢。

标签: ios xcode button swift observers


【解决方案1】:

您的问题是您误解了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)

我希望它是不言自明的。

根据cmets修改:

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)

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

【讨论】:

  • 谢谢。请回答我:我该如何编码,以便在按下pressedThreeSwipes 时,didSet 说'no_of_swipes 是三'。谢谢。
  • 如果你能在你的回答中包括如何做到这一点,我会打勾并 +1
  • 感谢您的编辑。初始化的一件事-我收到错误“初始化程序只能在类型中声明。”
  • 我明白你在做什么,但感觉太复杂了。当然,我应该修复我已经完成的事情。你有其他答案吗?
  • 感谢您收回投票。去别处寻求帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-14
  • 1970-01-01
  • 2020-05-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多