I.Star I.Star - 1 year ago 114
iOS Question

Use value entered in UITextField

How can I take an input value from the user with a text field and then use it to perform math functions in Swift?

I want to get a value from the user and then find the sine of that value.
Plus I want to display on a label.

Answer Source

According to your comment, you have the textfield as an IBOutlet. I've added a button to get the value:

@IBOutlet weak var textField: UITextField!

@IBOutlet weak var label: UILabel!

@IBAction func buttonPress(sender: AnyObject) {
    guard let text = textField.text, value = Double(text) else { return }

    label.text = String(sin(value))

The reason I've used guard is because if text is nil or if it's not a Double, it will just return, having done nothing (which is what I want). This way you don't have to worry about unexpected crashes when trying to calculate the value.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download