Binary operator '==' cannot be applied to operands of type 'UILabel?' and 'String'

∥☆過路亽.° 提交于 2021-02-05 12:36:40

问题


Error : Binary operator '==' cannot be applied to operands of type 'UILabel?' and 'String'


import UIKit

class ViewController: UIViewController {
  let Soft = 5
  let Medium = 8
    let Hard = 12


    @IBAction func hardnessSelected(_ sender: UIButton) {
        let hardness = sender.titleLabel

        if hardness == "Soft"{
            print(Soft)
        }
        else if hardness == "Medium"{
            print (Medium)
        }
        else {
            print (Hard)
        }

    }


}

How can i fix this error?


回答1:


You don't give the line number the error is on, but looking at the text it mentions operation == so I'm guessing it's one of these:

if hardness == "Soft"{

else if hardness == "Medium"{

"Soft" and "Medium" are the strings, so hardness must be a 'UILabel?. Those types can't be compared to each other. You must want the text displayed on the button? Looking at the UILabel docs, there is a text property so you probably want to change this line to grab the string representing the button's text:

let hardness = sender.titleLabel.text

Are you using dynamic buttons? It would be less error prone to just compare the sender with the button your are checking for. Comparing hard-coded strings to the text of the button can lead to run-time errors. Maybe you didn't get the case right, misspelled the text, or decided to localize later so the text may be different in a different language. These errors wouldn't be caught at compile-time.




回答2:


You're trying to compare two different types. To get the actual text of UILabel, you'll need hardness.text.




回答3:


UIButton.titleLabel is a UILabel and it stores its text in UILabel.text property:

let hardness = sender.titleLabel.text

In the case of UIButton you can also access UIButton.currentTitle property:

let hardness = sender.currentTitle



回答4:


An UIButton exposes its label through an UILabel that manage the drawing of its text. Thus change:

let hardness = sender.titleLabel

to

let hardness = sender.titleLabel.text

UIKit docs says:

UIButton

var titleLabel: UILabel?

A view that displays the value of the currentTitle property for a button.

and:

UILabel

var text: String?

The current text that is displayed by the label.

There is also a more direct way using the currentTitle:

UIButton

var currentTitle: String?

The current title that is displayed on the button.

Thus:

let hardness = sender.currentTitle

will also work.



来源:https://stackoverflow.com/questions/59723207/binary-operator-cannot-be-applied-to-operands-of-type-uilabel-and-strin

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!