Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,401 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.