将enum变量转换为anyObject - 使用swift

时间:2016-03-01 16:46:10

标签: ios swift enums

让我解释一下我的代码,然后陈述我面临的问题

我有两个viewControllers类

1- difficultyViewController:用户选择游戏难度的地方

** difficultyViewController有三个按钮供用户点击所需的难度

2- gameViewController:游戏将呈现给用户的位置 **目前在gameViewController中只有一个标签

难度控制器中的

我有一个表示三个游戏难度的枚举

class difficultyViewController: UIViewController {

    enum difficulties {
        case Easy
        case Medium
        case Hard
    }
     var gameDifficulty : difficulties?
    // other code is here
}

并且在gameViewController中我有一个对应于此枚举的变量

class gameViewController: UIViewController {

    @IBOutlet weak var gameDifficultyLabel: UILabel!
    var gameDifficulty : difficultyViewController.difficulties?
    // other code is here
} 
在dysViewController中的

我使用代码来执行和准备segue

@IBAction func easyButtonPressed(sender: AnyObject) {
        gameDifficulty = .Easy
        performSegueWithIdentifier("toGame", sender: gameDifficulty as? AnyObject)
    } 

这是准备segue代码

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "toGame" {
            if let gameVC = segue.destinationViewController as? gameViewController {
                if let difficulty = sender as? difficulties {
                    print(difficulty)
                    gameVC.gameDifficulty = difficulty
                }
            }
        }
    }

现在面临的问题是 当将难度作为参数发送到执行segue时,从枚举变量转换为无效且我总是收到零值

原因是什么?是不是可以将枚举转换为anyObject?

1 个答案:

答案 0 :(得分:2)

当用户按下按钮时,您正在设置游戏难度变量,那么为什么不根据该值设置难度级别呢?

此外,您的类名和枚举名应该大写,以区别于变量名。

class DifficultyViewController: UIViewController {

    enum Difficulties {
        case Easy
        case Medium
        case Hard
    }
     var gameDifficulty : Difficulties?
    // other code is here
}

class GameViewController: UIViewController {

    @IBOutlet weak var gameDifficultyLabel: UILabel!
    var gameDifficulty : DifficultyViewController.Difficulties?
    // other code is here
} 


@IBAction func easyButtonPressed(sender: AnyObject) {
        gameDifficulty = .Easy
        performSegueWithIdentifier("toGame", sender: AnyObject)
}




override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "toGame" {
            if let gameVC = segue.destinationViewController as? gameViewController {
                    gameVC.gameDifficulty = gameDifficulty // You changed this in the IBAction, so simply send it on to the next VC
                }
            }
        }
}