Swift:在整数

时间:2018-01-18 09:05:27

标签: swift null switch-statement case

我的代码问题:

  if let x = UserDefaults.standard.object(forKey: "carT") as? String {
            carTpass.text = x
        }

        if let x2 = UserDefaults.standard.object(forKey: "carM") as? String {
            carMpass.text = x2
        }
        if let x3 = UserDefaults.standard.object(forKey: "carCom") as? String {
            carCompass.text = x3
        }

 @IBAction func calc(_ sender: UIButton) {

        let statusCode:Int = Int(carMpass.text!)!

        switch (carTpass.text ,carCompass.text, statusCode) {
        case ("BMW"?,"X"?,2008 ... 2010):
            result.text = "Yes"
        default:
            result.text = "No"
        }

现在我的问题是:

如果statusCode为nil,应用程序将崩溃,因为解包的Integer,我该如何解决?

carTpass.text,carCompass.text和carMpass.text它们是来自另一个View Controller的数据(tableView)

2 个答案:

答案 0 :(得分:1)

在其他地方使用时只需使用if let

@IBAction func calc(_ sender: UIButton) {
    if let text = carMpass.text, let statusCode = Int(text) {
        switch (carTpass.text ,carCompass.text, statusCode) {
        case ("BMW"?,"X"?,2008 ... 2010):
            result.text = "Yes"
        default:
            result.text = "No"
        }
    }
}

答案 1 :(得分:1)

您也可以为范围应用可选的展开

let statusCode = carMpass.text.flatMap(Int.init)
switch (carTpass.text ,carCompass.text, statusCode) {
case ("BMW"?, "X"?, (2008 ... 2010)?):
    result.text = "Yes"
default:
    result.text = "No"
}