【问题标题】:Binary operator '*' cannot be applied to two 'Int?' operands二元运算符“*”不能应用于两个“Int?”操作数
【发布时间】:2019-06-15 20:37:04
【问题描述】:

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

【问题讨论】:

    标签: swift xcode swift5


    【解决方案1】:

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

    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
    }
    

    【讨论】:

      【解决方案2】:

      如果您不确定变量的值不是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 中测试。

      【讨论】:

      • 我们确定。尽管它被声明为可选,但UITextFieldtext 属性永远不会是nil。除此之外,您将每个单个字符转换为 Int,这没有任何意义。
      • @vadian 如果 Álvato Valero 使用 SwiftLint 会怎样?在这种情况下,默认情况下您不应执行强制展开。
      • SwiftLint 没有被提及,甚至 Apple 也确认 UITextFieldtext 属性永远不会是 nil
      猜你喜欢
      • 2018-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-10
      • 2015-09-01
      • 2017-11-22
      相关资源
      最近更新 更多