gpt4 book ai didi

ios - 将枚举变量转换为 anyObject - ios with swift

转载 作者:搜寻专家 更新时间:2023-11-01 07:26:32 24 4
gpt4 key购买 nike

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

我有两个 viewControllers 类

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

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

2- gameViewController :将游戏呈现给用户的地方**目前在gameViewController中只有一个label

在 difficultyViewController 中我有一个代表三个游戏难度的枚举

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
}

在 difficultyViewController 中,我使用代码来执行和准备 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
}
}
}
}

现在我面临的问题是当将难度作为参数发送给 perform segue 时,从枚举变量到无效的转换,我总是收到一个 nil 值

这是什么原因?无法将枚举转换为 anyObject 吗?

最佳答案

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

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

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
}
}
}
}

关于ios - 将枚举变量转换为 anyObject - ios with swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35728577/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com