[英]I got error “Type '(UITextRange) -> String?' cannot conform to 'BinaryInteger'; only struct/enum/class types can conform to protocol”
I'm new to Swift Programming and I made a simple project which will give output to a label, but I'm getting the error:我是 Swift 编程的新手,我做了一个简单的项目,它将 output 提供给 label,但我得到了错误:
Type '(UITextRange) -> String?'
键入“(UITextRange)-> 字符串?” cannot conform to 'BinaryInteger';
不能符合“BinaryInteger”; only struct/enum/class types can conform to protocol.
只有结构/枚举/类类型可以符合协议。
Can anyone explain what's happening?谁能解释发生了什么?
@IBOutlet weak var lblOutput: UILabel!
@IBOutlet weak var InputAge: UITextField!
@IBOutlet weak var outputAge: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func calcOutput(_ sender: Any) {
var age = Int(InputAge.text) * 8;
lblOutput.text = age;
}
Image containing the error:包含错误的图像:
There are three mistakes:有以下三个错误:
text
of inputAge
, this can be forced because the text property of UITextField
is never nil
inputAge
的text
,这可以强制执行,因为UITextField
的 text 属性永远不会nil
Int
, therefore Int(...)
returns an optional and you have to check if it's nil
Int
,因此Int(...)
返回一个可选值,您必须检查它是否为nil
text
property of UILabel
is String
. UILabel
的text
属性的类型是String
。 You have to convert the result of the multiplication back to String
String
And please name functions and variables with starting lowercase letter and declare immutable variables as constants ( let
)并且请以小写字母开头命名函数和变量,并将不可变变量声明为常量(
let
)
@IBOutlet weak var inputAge : UITextField!
@IBAction func calcOutput(_ sender: Any) {
let stringAge = inputAge.text!
if let age = Int(stringAge) {
lblOutput.text = String(age * 8)
} else {
lblOutput.text = "The input string is not convertible to Int"
}
}
Unwrap optional of text before use:使用前解开可选的文本:
@IBAction func calcOutput(_ sender: Any) {
if let text = validatedField.text,
let age = Int(text) {
lblOutput.text = "\(age * 8)"
}
}
Don't use semicolons at the lines end.不要在行尾使用分号。
Use let if you don't update its values later.如果您以后不更新其值,请使用let 。
Set text to text fields (not Int).将文本设置为文本字段(不是 Int)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.