二元运算符“*”不能应用于两个 'Int?' 操作数

Binary operator '*' cannot be applied to two 'Int?' operands

尝试将 BMI(体重指数)作为 Swift 中的应用程序计算。制作计算函数我找不到解决方案

@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?' 个操作数

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

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
}

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

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

此 post 中的所有代码均已在 Xcode 10.2.1.

中测试