skip to Main Content

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


  1. The closing parenthesis is at the wrong place

    let billTotalFormated = Float(billTotal.text!) ?? 0.0
    

    Force unwrapping the text property of an UITextField is allowed but you have to check if the string can be converted to Float

    Login or Signup to reply.
  2. The force unwrap you’re doing in Float(billTotal.text!) is to check if the billTotal text field contains any text. You can first check if billTotal 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 with 0.0.

    if billTotal.text.isEmpty == false {
        // The text field contains something. Now try and get the value from it.
        billTotalFormated = Float(billTotal.text!) ?? 0.0
    else {
        // Tell the user that the text field has an invalid value.
    
    Login or Signup to reply.
  3. I suggest you keep the float variable defined. Then check if the value in text field is not empty. You can do the following.

    var float: Float = 0.0
    
    if let text = billTotal.text {
      float = Float(text) ?? 0.0
    }
    
    Login or Signup to reply.
  4. You are converting from String to float so:

    let billTotalFormated = Float(billTotal.text ?? "")
    

    as textfield returns optional String so use this syntax

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search