Reputation:
Trying to calculate BMI ( body mass index ) as an app in Swift. Making the calculate function I cannot find the solution
@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)
}
Error message on the last line of code:
Binary operator '*' cannot be applied to two 'Int?' operands
Upvotes: 0
Views: 776
Reputation: 4521
Don't unwrap a variable if you are not sure that its value is not nil
. Use flatMap
to get a required value in one line:
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
}
All code in this post was tested in Xcode 10.2.1.
Upvotes: 0
Reputation: 285069
The problem are the pointless and wrong type annotations. Remove them! All values are non-optional (and constants)
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
}
Upvotes: 3