简体   繁体   中英

Cannot assign a value of type 'int' to a value of type 'String?'

Here is my code, I am a beginner using swift and my code does not work, the application should take the value of 'ageInput' textField and multiply it by 7 then show the results inside resultLabel, I always get the error:

Cannot assign a value of type 'int' to a value of type 'String?'

class ViewController: UIViewController {
    @IBOutlet weak var resultLabel: UILabel!
    @IBOutlet weak var ageInput: UITextField!
    @IBAction func findAge(sender: AnyObject) {

        var catAge = ageInput.text.toInt() ?? 0

        catAge = catAge * 7 ?? 0

        resultLabel.text = catAge

    }
       override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

Where did i go wrong?

尝试:

resultLabel.text = String (catAge)

你也可以这样做:

resultLabel.text = "\(catAge)"

here i have tray to solve your problem using example and i hope your issue will solved..

var stringNumber = "1234"
var numberFromString = stringNumber.toInt()
println(numberFromString)

Note toInt():

If the string represents an integer that fits into an Int, returns the  corresponding integer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM