Reputation: 33
Just starting learning swift but stuck when trying to multiply an input with another number and display on a label. I get the error that the number isn't a string and tried to cast but didn't work.
class ViewController: UIViewController {
@IBOutlet weak var entry: UITextField!
@IBOutlet weak var answer: UILabel!
@IBAction func button(_ sender: Any) {
answer.text = entry.text * 2
}
}
Upvotes: 0
Views: 1820
Reputation: 58149
You should cast the text into a Double
, an Int
etc., then convert the calculation to a string.
if let entry = Double(entry.text) {
answer.text = "\(entry * 2)"
}
or
if let entry = Int(entry.text) {
answer.text = "\(entry * 2)"
}
Upvotes: 1
Reputation: 59
If you know that the entry will hold a number
answer.text = String(Int(entry.text)! * 2)
Using optional unwrapping instead
if let num = Int(entry.text) {
answer.text = String(num * 2)
}
Upvotes: 1