I am trying to convert some data types and cannot find anything helpful online. Data types in question are UITextField to Float – I tried doing it this way, but it does not work.
let billTotalFormated = Float(billTotal.text ?? 0.0)
the error I am getting is: Cannot convert value of type ‘Double’ to expected argument type ‘String’.
I can force unwrap the value with the line:
let billTotalFormated = Float(billTotal.text!)
, but heard that is not safe to do since it could throw errors.
4
Answers
The closing parenthesis is at the wrong place
Force unwrapping the
text
property of anUITextField
is allowed but you have to check if the string can be converted toFloat
The force unwrap you’re doing in
Float(billTotal.text!)
is to check if thebillTotal
text field contains any text. You can first check ifbillTotal
contains text, and after that it’s safe to unwrap it.The purpose of the nil coalescing operator you’re doing in
let billTotalFormated = Float(billTotal.text ?? 0.0)
would be to replace any invalid string in the text field with0.0
.I suggest you keep the float variable defined. Then check if the value in text field is not empty. You can do the following.
You are converting from String to float so:
as textfield returns optional String so use this syntax