Most likely, you'll want to not only check the type, but also cast to that type. In this case, use:
if let gestureRecognizer as? UITapGestureRecognizer { }
else { /* not a UITapGestureRecognizer */ }
Swift casting operators
These operators are only available in Swift, but still work when dealing with Objective C types.
The as
operator
The as
operator performs a cast when it is known at compile time that the cast always succeeds, such as upcasting or bridging. Upcasting lets you use an expression as an instance of its type’s supertype, without using an intermediate variable.
- This is the most preferable operator to use, when possible. It guarentees success, without worrying about unwrapping an optional or risking a crash.
The as?
operator
The as!
operator
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
operator
- The
is
operator checks at runtime whether the expression can be cast to the specified type. It returns true
if the expression can be cast to the specified type; otherwise, it returns false
- Works on any Swift type, including Objective C types.
- Swift equivalent of
isKind(of:)
-
- Unlike the
is
operator, this can be used to check the exact type, without consideration for subclasses.
- Can be used like:
type(of: instance) == DesiredType.self
- Swift equivalent of
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 from NSObjectProtocol
(such as subclasses of NSObject
). I advise against using these, but I mention them here for completeness
-
- Returns a Boolean value that indicates whether the receiver is an instance of given class or an instance of any class that inherits from that class
- Avoid this in Swift, use
is
operator instead.
-
- Returns a Boolean value that indicates whether the receiver is an instance of a given class
- Avoid this in Swift, use
type(of: instance) == DesiredType.self
instead.
-
- Returns a Boolean value that indicates whether the receiver conforms to a given protocol.
- Avoid this in Swift, use
is
operator instead.