Checking object type?

18 views
Skip to first unread message

Alex Hall

unread,
Jun 26, 2015, 6:39:02 PM6/26/15
to swift-l...@googlegroups.com
Hello everyone,
I have a method that needs to check what kind of recognizer a UIGestureRecognizer is. In looking up how to do that, I have found that Swift appears to lack any kind of type comparison or member checking. I found Type and dynamicType, but those don't appear to be usable in comparisons. For instance, this won't work:

if gestureRecognizer.metaType==UITapGestureRecognizer.metaType

I tried mixing Type in there as well, but that fails too. There must be a way to do this that I'm overlooking, but I'm not sure what it is. Any suggestions would be great. Thanks.

--
Have a great day,
Alex Hall

Jens Alfke

unread,
Jun 26, 2015, 6:44:13 PM6/26/15
to Alex Hall, swift-l...@googlegroups.com

On Jun 25, 2015, at 7:17 AM, Alex Hall <meh...@icloud.com> wrote:

I have a method that needs to check what kind of recognizer a UIGestureRecognizer is. In looking up how to do that, I have found that Swift appears to lack any kind of type comparison or member checking. I found Type and dynamicType, but those don't appear to be usable in comparisons.

You use the “is” operator to check whether an instance is of a subclass type:

if gestureRecognizer is UITapGestureRecognizer {
}

You can also use "gestureRecognizer as? UITapGestureRecognizer” to check and type-cast in one operation.

This is covered in the “Type Casting” chapter of the book.

—Jens
Reply all
Reply to author
Forward
0 new messages