Search code examples
swiftdowncast

Downcast from AnyObject?


I am a bit puzzled as to what is going on with the code below. I was under the impression that children would be an optional based on node.children (which is of type [AnyObject]) being of type [SKNode] What I am seeing is that children is never nil, is this because [AnyObject] does not contain any type information? Even if I change [SKNode] to [NSString] it still goes to (1)?

    if let children = node.children as? [SKNode] {
        // (1) STUFF WITH SKNODE...
    } else {
        // (2) NOPE, ITS NOT AN SKNODE

Solution

  • node.children is not an optional. It always returns an array of type [AnyObject]. If there are no children, this array will have 0 elements. If there are children, then this array will contain SKNodes.

    The optional binding if let children = node.children as? [SKNode] will always succeed because an empty array of objects [AnyObject] can be cast to [SKNode].

    When I first saw that node.children was returning [AnyObject] instead of [SKNode] I thought that was odd. Then I realized that this is a Cocoa Touch interface that works with Objective-C so it isn't going to be able to return [SKNode] even though that is what it contains.