我在代码中的问题:
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"
}
现在我的问题是:
如果状态代码为nil,应用程序将崩溃,因为解开的整数,我该如何解决?
carTpass.text 、carCompass.text 和 carMpass.text 它们是来自另一个视图控制器 (tableView( 的数据
只需像在其他地方使用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"
}
}
}
您也可以对范围应用可选的解包
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"
}