Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Unbinding the text of a Textfield and convert it to Double

I want to use a Text Fields "text" property (optional string) and turn it into a double to then do some calculations on it. Would the following be considered the correct (best practice) way to do this? :

    if let text = amountField.text, let number = Double(text) {
        tipCalc.total = number
    } else {
        tipCalc.total = 0.0
    }

Or is there a better way to do the same?

1 Answer

I had tried that but it gives me the error:

Value of optional type 'String?' not unwrapped: did you mean to use '!' or '?'?

Or am I misunderstanding something here?

Zachary Betz
Zachary Betz
10,413 Points

Was using an online Swift compiler, so was not able to verify that code against an actual UITextField. From reading up on it, it looks like your original post is the shortest way to do it.