Ios Swift:通过全局文件进行永久变量更改

Ios Swift:通过全局文件进行永久变量更改,ios,xcode,variables,swift,properties,Ios,Xcode,Variables,Swift,Properties,我在三个文件之间工作:Menu.swift、Main.swift和Game.swift 在myMain.swift中,我定义了变量swipeNumber: class Main { var swipeNumber: Int = 0 { didSet{ println("The new swipe number is \(swipeNumber)") } } } 注意:它是类中的,因此我可以引用其他文件中的变量,并且didS

我在三个文件之间工作:
Menu.swift
Main.swift
Game.swift

在myMain.swift中,我定义了变量
swipeNumber

class Main {
    var swipeNumber: Int = 0 {
        didSet{
            println("The new swipe number is \(swipeNumber)")
        }
    }
}
注意:它是类中的,因此我可以引用其他文件中的变量,并且didSet属性观察器将起作用

如您所见,它的初始值(我认为)是
0

然后,在我的Menu.swift中,我从Main.swift中的主类中检索信息

然后我有三个按钮
,触摸后,将根据按下的按钮更改
SwipenNumber
变量

class Menu: UIViewController {

    @IBAction func pressedThreeSwipes(sender: AnyObject) {
        main.swipeNumber = 3
    }

    @IBAction func pressedFiveSwipes(sender: AnyObject) {
        main.swipeNumber = 5
    }

    @IBAction func pressedTenSwipes(sender: AnyObject) {
        main.swipeNumber = 10
    }

    //...

}
当我运行程序时,我的属性观察者似乎工作,打印消息,例如:

The new swipe number is 3
The new swipe number is 5
The new swipe number is 10
在游戏类中(出于故障排除的目的),我有另一个属性观察器,在按下按钮
test
时检查变量
swipeNumber的整数:

class Game: UIView {

    let main = Main()

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

        println("now")
        println("\(main.swipeNumber)"
        //Nothing happens here, suggesting that didMoveToView is failing

    }

    @IBAction func test(sender: AnyObject) {
        println("\(main.swipeNumber)")
    }

}
我的
函数测试
打印一个数字,但遗憾的是,这个数字不是3、5或10
0

我认为问题在于我在Main.swift中的变量,但是我不确定

任何建议或“修复”,无论是快速的还是冗长的,都将不胜感激

谢谢,


您的类有不同的实例
Main
,它们对相同的属性都有不同的值


您应该尝试使用单例模式(例如,请参见或)。

当您调用Main()时,您正在创建一个新对象……强调新建。它不知道您对相同类型的其他对象做了什么。如果你想在不同的地方使用同一个对象,你需要将它作为一个参数并将其传递到方法中,而不是创建一个不同的对象。

这似乎是个好主意,你认为你可以编辑你的答案来使用我的变量和代码吗?谢谢。我如何将某些内容转换为参数?如果您能给我(变量)任何帮助,我将不胜感激。谢谢。这取决于菜单和游戏对象的创建方式(即程序结构)。一种可能是给游戏一个初始值设定项,如
init(withMain Main object:Main){/*保存Main object以便在这个游戏中使用*/}
,并传递您以前使用过的对象。
class Game: UIView {

    let main = Main()

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

        println("now")
        println("\(main.swipeNumber)"
        //Nothing happens here, suggesting that didMoveToView is failing

    }

    @IBAction func test(sender: AnyObject) {
        println("\(main.swipeNumber)")
    }

}