xcode 如何将 textField.text 值转换为整数并将两个整数相加

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40109695/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 09:28:25  来源:igfitidea点击:

How to convert textField.text value to Integer and sum two Integers

swiftxcodemacosxcode7calculator

提问by rincdani923

Initialization of immutable value 'textfieldInt' was never used; consider replacing with assignment to '_' or removing it and textfield2Int

从未使用过不可变值“textfieldInt”的初始化;考虑替换为“_”的赋值或删除它和 textfield2Int

I get that warning twice for textfieldInt

我两次收到 textfieldInt 的警告

This is all the code I have:

这是我拥有的所有代码:

class ViewController: UIViewController {

    @IBOutlet weak var textField1: UITextField!
    @IBOutlet weak var textField2: UITextField!
    @IBOutlet weak var output: UILabel!

    @IBAction func calculate(_ sender: AnyObject) {
        let textfieldInt: Int? = Int(textField1.text!)
        let textfield2Int: Int? = Int(textField2.text!)
        let convert = textField1.text! + textField2.text!
        let convertText = String(convert)
        output.text = convertText

}

回答by David Seek

You are receiving the warning because, as the warning tells you, you are instantiating textfieldIntand textfield2Int, but you're not using your created Integers textfieldIntand textfield2Intto be calculated as let convert, but you add the Strings textField1.text!and textField2.text!together...

您收到警告是因为,正如警告告诉您的那样,您正在实例化textfieldIntand textfield2Int,但您没有使用您创建的整数textfieldInttextfield2Int计算为let convert,但是您将字符串textField1.text!textField2.text!一起添加...

I guess, you want your function to be that:

我想,您希望您的功能是:

@IBAction func calculate(_ sender: AnyObject) {
    let textfieldInt: Int? = Int(textField1.text!)
    let textfield2Int: Int? = Int(textField2.text!)
    let convert = textfieldInt + textfield2Int
    let convertText = String(convert)
    output.text = convertText
}