Using isKindOfClass with Swift Using isKindOfClass with Swift ios ios

Using isKindOfClass with Swift


The proper Swift operator is is:

if touch.view is UIPickerView {    // touch.view is of type UIPickerView}

Of course, if you also need to assign the view to a new constant, then the if let ... as? ... syntax is your boy, as Kevin mentioned. But if you don't need the value and only need to check the type, then you should use the is operator.


override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {    super.touchesBegan(touches, withEvent: event)    let touch : UITouch = touches.anyObject() as UITouch    if touch.view.isKindOfClass(UIPickerView)    {    }}

Edit

As pointed out in @Kevin's answer, the correct way would be to use optional type cast operator as?. You can read more about it on the section Optional Chaining sub section Downcasting.

Edit 2

As pointed on the other answer by user @KPM, using the is operator is the right way to do it.


You can combine the check and cast into one statement:

let touch = object.anyObject() as UITouchif let picker = touch.view as? UIPickerView {    ...}

Then you can use picker within the if block.