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

前端 未结 4 749
天涯浪人
天涯浪人 2021-01-29 16:46

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


import UIKit

class ViewController: UIViewController {
  let So         


        
4条回答
  •  迷失自我
    2021-01-29 17:23

    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.

提交回复
热议问题