Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Compare AnyObject with `is` Syntax

Tags:

ios

swift

I want to check if my sender is an Xyz-Object

override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
let senderIsBonusProduct = sender is Xyz

but I get following error:

Could not find a user-defined conversion from type 'Int1' to type 'Bool'

like image 517
Jannik S. Avatar asked Jun 12 '14 21:06

Jannik S.


3 Answers

The expression sender is Xyz is returning a Bool depending on if sender is of type Xyz. It appears that there is a compiler bug whereby sender is Xyz is actually returning a Int1 that is not getting coerced internally to a Bool.

A workaround is:

let bonus = (sender is Xyz ? true : false)
like image 57
GoZoner Avatar answered Nov 13 '22 02:11

GoZoner


You can also change it to

if let senderOfTypeXYZ = sender as? Xyz {
    // senderOfTypeXYZ is available with the expected type here
 }
like image 39
benjipetit Avatar answered Nov 13 '22 03:11

benjipetit


Workarounds aren't required anymore with the Beta 3 release and you can combine the is operator with other logical operators.

like image 1
gui_dos Avatar answered Nov 13 '22 04:11

gui_dos