切换swift时在两个变量之间来回切换的最佳方法

时间:2017-09-11 19:33:17

标签: swift sprite-kit

我有一个变量gameMode,我想在点击屏幕时在Vertical和Horizo​​ntal之间切换。我遇到的问题是它只需要较低的变量,gameMode总是显示为水平。我怎么能解决这个问题,以便在调用touchesBegan方法时切换它?任何帮助表示赞赏!

以下是我遇到问题的代码:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {


    if gameMode == "Horizontal" {

        gameMode = "Vertical"

    }


    if gameMode == "Vertical" {

        gameMode = "Horizontal"

    }


    print(gameMode) }

3 个答案:

答案 0 :(得分:2)

会发生这种情况,因为如果gameMode"Horizontal",则您将gameMode设置为"Vertical",此后gameMode == "Vertical"会返回true,因此您需要设置gameMode "Horizontal"override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if gameMode == "Horizontal" { gameMode = "Vertical" } else { gameMode = "Horizontal" } print(gameMode) }

试试这段代码:

enum

您应该使用enum GameMode { case horizontal case vertical mutating func toggle() { self = self == .horizontal ? .vertical : .horizontal } } var gameMode: GameMode = .horizontal override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { gameMode.toggle() print(gameMode) } 而不是字符串。

示例:

{{1}}

答案 1 :(得分:1)

您可以使用三元运算符

切换这两种状态
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    gameMode = gameMode == "Horizontal" ? "Vertical" : "Horizontal"
    print(gameMode) 
}

对于只有两个状态,布尔变量可能更合适。如果gameModeBool,您只需撰写

即可
gameMode = !gameMode

答案 2 :(得分:0)

我会替换

if gameMode == "Horizontal" {

    gameMode = "Vertical"

}


if gameMode == "Vertical" {

    gameMode = "Horizontal"

}

if gameMode == "Horizontal" {

    gameMode = "Vertical"

} else {

    gameMode = "Horizontal"

}

在一行中有两个 if 语句,当您将“Horizo​​ntal”作为值发送时,它会将其切换为“Vertical”。这也将使第二个声明启动并将其切换回来。使用if / else将确保它只运行一次。