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

标签 swift xcode swift5

尝试将 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?”操作数

最佳答案

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

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
}

关于swift - 二元运算符 '*' 不能应用于两个 'Int?' 操作数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56538034/

相关文章:

ios - 如何手动将 PFFile 从 PFQueryTableViewController 转移到另一个 ViewController?

ios - 在 ios 中将 Storyboard从一个应用程序复制到另一个应用程序的最佳方法是什么?

ios - 将 SwiftUI View 渲染为 UIImage

swift - 如何访问存储在类型为 "Any"的变量中的值

ios - 无法在 swift 的子文件夹中找到图像?

xcode - 尝试在 Swift 的多点连接测试应用程序中使用 NSNotification

ios - 无法将类型 'String?' 的值转换为预期的参数类型 'Int64' swift ios

swift - 从表格 View 单元格返回总值[swift]

ios - 我们不再需要将框架链接到 XCode 项目了吗?

ios - 从UIActivityController中排除Facebook Messenger,Instagram和Whats App