This line of code used to work with Swift 2, but now is incorrect in Swift 3.
if gestureRecognizer.isMember(of: UITapGestureRecognizer) { }
I get this error: Expected member name or constructor call after type name.
What is the correct way to use isMember(of:)
?
Most likely, you'll want to not only check the type, but also cast to that type. In this case, use:
Swift casting operators
These operators are only available in Swift, but still work when dealing with Objective C types.
The
as
operatorThe
as?
operatorThis is the second most preferable operator to use. Use it to safely handle the case in which a casting operator can't be performed.
The
as!
operatorThis is the least preferable operator to use. I strongly advise against abusing it. Attempting to cast an expression to an incompatible type crashes your program.
Swift type checking
If you merely want to check the type of an expression, without casting to that type, then you can use these approaches. They are only available in Swift, but still work when dealing with Objective C types.
The
is
operatoris
operator checks at runtime whether the expression can be cast to the specified type. It returnstrue
if the expression can be cast to the specified type; otherwise, it returnsfalse
isKind(of:)
Using
type(of:)
is
operator, this can be used to check the exact type, without consideration for subclasses.type(of: instance) == DesiredType.self
isMember(of:)
Legacy (Objective C) methods for checking types
These are all methods on
NSObjectProtocol
. They can be used in Swift code, but they only apply work with classes that derive fromNSObjectProtocol
(such as subclasses ofNSObject
). I advise against using these, but I mention them here for completenessisKind(of:)
is
operator instead.isMember(of:)
NSObjectProtocol
, thus only works on classes that derive fromNSObjectProtocol
(such as subclasses ofNSObject
)type(of: instance) == DesiredType.self
instead.conforms(to:)
NSObjectProtocol
, thus only works on classes that derive fromNSObjectProtocol
(such as subclasses ofNSObject
)is
operator instead.There are several ways to check the class of an object. Most of the time you will want to use either the
is
or theas?
operators like so:You have to use .self to refer the class type now.
There is also:
Swift 3: