Middi
Middi

Reputation: 353

Creating double from strings

first of all totally new here, had a search but maybe I don't know what I'm looking for.

Basically I've made a simple exchange rate app that has a fixed exchange rate.

You type in the text field your currency and it converts it for you.

I'm struggling with creating the result from the textfield x my exchange rate. I think it's something to do with forcing a double but i've tried so many ways.

Thanks in advance

class ViewController: UIViewController {

let exchangeRate = 5.99


@IBOutlet weak var display: UILabel!
@IBOutlet weak var textField: UITextField!

@IBAction func button(sender: AnyObject) {
    display.text = (textField.text * exchangeRate)



}

Upvotes: 1

Views: 73

Answers (1)

keithbhunter
keithbhunter

Reputation: 12334

You can cast the String to a Double using an initializer and unwrapping, and then update the text field with the new value.

class ViewController: UIViewController {

    let exchangeRate = 5.99

    @IBOutlet weak var display: UILabel!
    @IBOutlet weak var textField: UITextField!

    @IBAction func button(sender: AnyObject) {
        if let text = textField.text {
            if let input = Double(text) {
                display.text = String(input * exchangeRange)
            }
        }
    }
}

Upvotes: 2

Related Questions