简体   繁体   中英

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:

Type '(UITextRange) -> String?' cannot conform to '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:

  1. You have to unwrap text of inputAge , this can be forced because the text property of UITextField is never nil
  2. For example "ABC" cannot be converted to Int , therefore Int(...) returns an optional and you have to check if it's nil
  3. The type of the text property of UILabel is String . You have to convert the result of the multiplication back to String

And please name functions and variables with starting lowercase letter and declare immutable variables as constants ( 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.

Set text to text fields (not Int).

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