我正在做这个应用程序,用户需要传递两个Int
值,当按下按钮并且没有输入任何值时应用程序崩溃。
我该如何解决这个问题?
我认为它与可选值有关。
这是我的代码:
class ViewController: UIViewController {
@IBOutlet var age_1: UITextField!
@IBOutlet var age_2: UITextField!
@IBOutlet var emoji_button: UIButton!
@IBOutlet var date_textField: UILabel!
let colorProvider = BackgroundColorProvider()
@IBAction func button_pressed(_ sender: AnyObject) {
// Compare 2 given ages(int) and tell if people can date.
let me_age = Int(age_1.text!)!
let other_age = Int(age_2.text!)!
let me_age_min = (me_age / 2) + 7
let me_age_max = (me_age - 7) * 2
if me_age == 0 || other_age == 0 {
date_textField.text = "Enter ages then touch the heart"
}else if me_age > 18 && other_age < 18{
date_textField.text = "Don't date an under-age."
}// Case 2: Person is older and cant´date younger:
else if me_age < 18 && other_age > 18{
date_textField.text = "You are under age."
}else if me_age == other_age{
date_textField.text = "You definetly should date."
}else if other_age < me_age_min {
print (me_age_min)
date_textField.text = "To young 4 U"
} // Case 3: Person is young and can't date older:
else if other_age > me_age_max {
print ((me_age - 7) * 2 )
date_textField.text = "To old 4 U"
} // Case 4: Both people are the same age:
else{
date_textField.text = "Yes, you can date. "
}
答案 0 :(得分:0)
我会重写这两行:
let me_age = Int(age_1.text!)!
let other_age = Int(age_2.text!)!
使用:
guard let me_age = Int(age_1.text ?? "") else {
date_textField.text = "Enter valid number into age1" //Replace this line to any code you prefer
return
}
guard let other_age = Int(age_2.text ?? "") else {
date_textField.text = "Enter valid number into age2" //As well as the line above
return
}
age_1.text
为nil
,则age_1.text!
会崩溃。age_1.text!
不是有效整数,则Int(age_1.text!)!
会崩溃。age_2.text
为nil
,则age_2.text!
会崩溃。age_2.text!
不是有效整数,则Int(age_2.text!)!
会崩溃。因此,人们将!
称为崩溃我运算符,如果您不想让应用崩溃,最好避免使用它。
(语义上age_1
或age_2
可以是nil
,但如果您正确连接@IBOutlet
这不是问题。)
答案 1 :(得分:-1)
如果Int(someStr)
会得到nil
,无论字符串是""
还是其他字符串,所以你不能nil!
,你可以判断textField.text
是否int
在获得value
let me_age = Int(age_1.text!)!
let other_age = Int(age_2.text!)!
之前,1}}为空。
替换两行:
var me_age:Int
if let age1 = Int(age_1.text!) {
me_age = age1
}else {
// there alert to ask user type in age_1
print("ask user to type in current age_1 ")
return
}
var other_age:Int
if let age2 = Int(age_2.text!) {
other_age = age2
}else {
// there alert to ask user type in age_1
print("ask user to type in current age_2")
return
}
要:
age
首先,如果您想在textField
中输入textField
,则应将keyboard
的{{1}}类型设置为Number Pad
。