Eric Greenwood
Eric Greenwood

Reputation: 23

Swift - Multiply values from two UITextFeild's

I'm trying to calculate two values from two UITextFields. What I did was made the answerScreen equal to the valueOne which I turned into an Int and valueTwo which is supposed to be the opposite of an var with the !. Can somebody tell me what I'm doing wrong?

import UIKit

class ViewController: UIViewController {
    // The answer will be here
    @IBOutlet weak var answerScreen: UILabel!
    // The first number
    @IBOutlet weak var valueOne: UITextField!
    // The second number
    @IBOutlet weak var valueTwo: UITextField!
    // The equals button
    @IBAction func calculateValues(sender: AnyObject) {
        answerScreen.text = valueOne.text.toInt() * valueTwo!
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

Upvotes: 2

Views: 2975

Answers (2)

Avijit Nagare
Avijit Nagare

Reputation: 8782

One Can try

var temp =  (firstTextField.text! as NSString).integerValue * (secondTextField.text! as NSString).integerValue

For setting value to UILabel

self.resultLable.text = String("\((firstTextField.text! as NSString).integerValue * (secondTextField.text! as NSString).integerValue)")

Upvotes: -1

fluidsonic
fluidsonic

Reputation: 4676

let result = (valueOne.text.toInt() ?? 0) * (valueTwo.text.toInt() ?? 0)
answerScreen.text = "\(result)"

Will convert the text field values to Int or use 0 if the conversion failed.

Upvotes: 4

Related Questions