I am new to programming and swift 3. I got an error message when I was trying to make a simple math game. I just want it to generate a new number 0 - 10 everytime you click answerOne or answerTwo, but the UIlabel can't be changed to an Interger, so it gives me the error message "Cannot assign value of type 'Int' to type 'String?'". I dont know how to fix this, but here's the code if you need it
import UIKit
class ViewController: UIViewController {
@IBOutlet var theQuestion: UILabel!
let theQuestionNumberOne = arc4random_uniform(11)
@IBOutlet var firstChoice: UIButton!
@IBOutlet var secondChoice: UIButton!
@IBAction func answerOne(_ sender: AnyObject) {
theQuestion.text = Int(theQuestionNumberOne) //Error here
}
@IBAction func answerTwo(_ sender: AnyObject) {
theQuestion.text = Int(theQuestionNumberOne) //Error here
}
override func viewDidLoad() {
super.viewDidLoad()
/
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
/
}
}
The 'text' property of a UILabel is type 'String'. Therefore, you need to assign it a String. The simplest method to convert various types to strings is using Swift's interpolation:
let theValue = 3
let theValueString = "\(theValue)"However, for a more robust solution, use a number formatter to ensure your string will be formatted according to the user's current region.
Also note that the value of 'theQuestionNumberOne' will remain constant for the lifetime of your view controller. From your notes above, if you want that value to change every time your actions are called, make that a 'var' instead of 'let'. Also, in those actions, set its value to a new random value.