问题
Initialization of immutable value 'textfieldInt' was never used; consider replacing with assignment to '_' or removing it and textfield2Int
I get that warning twice for 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
}
回答1:
You are receiving the warning because, as the warning tells you, you are instantiating textfieldInt
and textfield2Int
, but you're not using your created Integers textfieldInt
and textfield2Int
to be calculated as let convert
, but you add the Strings textField1.text!
and textField2.text!
together...
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
}
来源:https://stackoverflow.com/questions/40109695/how-to-convert-textfield-text-value-to-integer-and-sum-two-integers