Reputation: 19
Using a tutorial from iOS 8/Swift 1 to create a sample app in an attempt to assign text to a label, using Xcode 7.3/Swift 2.2. Thanks in advance.
import UIKit
class ViewController: UIViewController {
@IBOutlet var ageCat: UITextField!
@IBOutlet var resultAge: UILabel!
@IBAction func findAgeButton(sender: AnyObject) {
var enteredAge = Int(ageCat.text!)
var catYears = enteredAge! * 7
resultAge = "Your cat is \(catYears) in cat years"
}
}
Upvotes: 1
Views: 359
Reputation: 19
Thanks for all the helpful input. This worked for me:
@IBAction func findAgeButton(sender: AnyObject) {
var catYears = Int(ageCat.text!)!
catYears = catYears * 7
resultAge.text = "Your cat is \(catYears) in cat years"
}
I also added an if/else to address nil entries:
if Int(ageCat.text!) != nil {
// --insert last 3 lines of code from above here--
} else {
resultAge.text = "Please enter a number"
}
Upvotes: 0
Reputation: 534
You need to assign value to resultAge.text instead of resultAge:
resultAge.text = "Your cat is \(catYears) in cat years"
Upvotes: -1
Reputation: 2408
Replace your IBAction func findAgeButton with the following:
@IBAction func findAgeButton(sender: AnyObject) {
// Here the variable is unwrapped. This means the code after it is not executed unless the program is sure that it contains a value.
if let text = ageCat.text {
// You can use the unwrapped variable now and won't have to place an exclamation mark behind it to force unwrap it.
let enteredAge = Int(text)
if let age = enteredAge {
let catYears = age * 7
resultAge.text = "Your cat is \(catYears) in cat years"
}
}
}
Upvotes: 3