Learn Courses My Dashboard

Turn a TextField's text into a double in Swift UI

I working on an app that takes user input and uses that input for calculation.

I want to take the text string and turn out into a double. Everything I have found online points to this code:

TextField(“Length”, text: $project.length)

let length = Double(lengthTextField.text ?? " ") 0.0

When I put this code into a button function I get myriad errors. I thought the problem was that ‘text’ part of TextField said ‘$.project.length’. So I tried writing the following:

let length = Double($project.length.text ?? " ") 0.0

let length = Double($project.length ?? " ") 0.0

let length = Double(project.length.text ?? " ") 0.0

let length = Double(project.length ?? " ") 0.0

These all produce errors. Can someone please tell me the correct way to write this?

Like this:

let length = Double(project.length) ?? 0.0

You have to try to convert something (in this case project.length) to Double first, then check if it succeeded with nil coalescing and then, if it didn’t, default to 0.0.

Thanks, Rooster, that works.