简体   繁体   English

无法将类型为'int'的值分配给'String?'类型的值

[英]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: 这是我的代码,我是初学者使用swift而我的代码不起作用,应用程序应该取'ageInput'textField的值并将其乘以7然后在resultLabel中显示结果,我总是得到错误:

Cannot assign a value of type 'int' to a value of type 'String?' 无法将类型为'int'的值分配给'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(): 注意toInt():

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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