I'am a swift beginner then want to write a BMI counting.
A error Cannot assign value of type 'Double' to 'String?'
appear in label.text = GetBMI(H: myH, W: myW)
How can I fix it ?
@IBAction func calBMI(_ sender: AnyObject) {
if Height.text != nil && Weight.text != nil {
let myH : Double = (Height.text! as AnyObject).doubleValue
let myW : Double = (Weight.text! as AnyObject).doubleValue
label.text = GetBMI(H: myH, W: myW)
}
else {
label.text = "Please enter your Height and Weight!"
}
}
func GetBMI(H: Double, W: Double) -> Double {
let height: Double = H / 100
return W / (height * height)
}
Your function returns a double, the label.text will only accept a string. Hence the error message you get: Cannot assign value of type 'Double' to 'String?.
The question mark in the error might of thrown you off. The ? on 'String?' is there because the label.text MIGHT be empty, so its an 'optional' ie: may or may not have a value. Opposite of ! which explicitly declares there is a value and is != nil.
You can find some threads describing how to fix Cannot assign value of type 'Double' to 'String?', but unfortunately those threads may not point out some bad parts of your code.
If I were to fix all such parts:
Some points:
Property names should represent the content's feature. In your code, you use
height
andweight
asDouble
values, so you'd better nameUITextField
s (assumingHeight
andWeight
areUITextField
s) with something other. I renamed them toheightField
andweightField
.Testing with
!= nil
and then applying forced unwrapping (!
) is not a preferred way, you'd better avoid using!
as much as possible. Better use Optional binding --if-let
.You should not use
(... as AnyObject).doubleValue
to convertString
toDouble
. You can use the initializer ofDouble
to convertString
toDouble
(#1). Which returnsOptional<Double>
, so better include them inif-let
.You cannot directly assign
Double
value to a property of typeString?
. You can use the initializer ofString
to convertDouble
toString
(#1).In Swift, you usually use capitalized identifier only for types, so I renamed
GetBMI(H:W:)
togetBMI(h:w:)
.(#1) Using initializers when converting between
String
andDouble
is sort of a simplified way. It may be sufficient for making a BMI Calculator tutorial code, but may not be sufficient for actual apps. Consider usingNSNumberFormatter
for actual apps.Bold lines are mandatory or strongly recommended.