簡體   English   中英

將枚舉變量轉換為anyObject-Swift的iOS

[英]converting enum variable to anyObject - ios with swift

讓我解釋一下我的代碼,然后說明我面臨的問題

我有兩個viewControllers類

1-難度查看控制器:用戶選擇游戲的難度

** difficultyViewController具有三個按鈕,供用戶單擊所需的難度

2- gameViewController:游戲將呈現給用戶的地方**當前在gameViewController中只有一個標簽

在differenceViewController中,我有一個枚舉,表示三個游戲難度

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
} 

在differentialViewController中,我正在使用代碼來執行和准備segue

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

這是准備密碼的方法

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時,從枚舉變量到無效變量的轉換,並且我總是收到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
                }
            }
        }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM