Search code examples
swifttypechecking

Is there a way to prevent UILabel from type checking as UIView?


In my application I'm using the as operator to check what type of UI element I'm working with. I ran into an issue where UILabel is successfully checking as a view.

let label = UILabel()
label.text = "some text"

if let myLabel = label as? UIView {
    print("its a view ") // succeeds
}

I also receive the warning that states:

warning: Conditional cast from 'UILabel' to 'UIView' always succeeds.

Question

Is there a way to add a constraint to this as check that will cause this check to fail as expected?


Solution

  • Try this:

    if label.isMemberOfClass(UIView.self) {
        print("its a view ") // succeeds
    }
    

    isMemberOfClass checks for UIView and no classes that inherit from it