二进制运算符'*'不能应用于两个'Int?'操作数

时间:2019-06-11 06:49:17

标签: swift xcode swift5

尝试在Swift中将BMI(体重指数)计算为应用程序。使计算功能我找不到解决方案

@IBOutlet weak var height: UITextField!
@IBOutlet weak var weight: UITextField!

@IBAction func calculate(_ sender: UIButton) {

    }

@IBAction func reset(_ sender: UIButton) {
    }

func calculateIMC(){

    var textHeight = height.text
    var textWeight = weight.text
    var intHeight:Int? = Int(textHeight!) ?? 0
    var intWeight:Int? = Int(textWeight!) ?? 0

    let calculateHeight: Int? = (intHeight * intHeight)
}

代码最后一行的错误消息:

二进制运算符'*'不能应用于两个'Int?'操作数

2 个答案:

答案 0 :(得分:2)

问题在于毫无意义且错误的类型注释。删除它们!所有值都是非可选的(和常量)

func calculateIMC(){

    let textHeight = height.text
    let textWeight = weight.text
    let intHeight = Int(textHeight!) ?? 0
    let intWeight = Int(textWeight!) ?? 0

    let calculateHeight = intHeight * intHeight // probably intHeight * intWeight
}

答案 1 :(得分:0)

如果不确定变量的值不是nil,请不要打开变量。使用flatMap在一行中获取所需的值:

func calculateIMC() {
    let textHeight = height.text
    let textWeight = weight.text
    let intHeight = textHeight.flatMap { Int($0) } ?? 0
    let intWeight = textWeight.flatMap { Int($0) } ?? 0
    let calculateHeight = intHeight * intHeight
}

本文中的所有代码均已在Xcode 10.2.1中进行了测试。