2

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
fuzzygoat
  • 26,573
  • 48
  • 165
  • 294

1 Answers1

3

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.

vacawama
  • 150,663
  • 30
  • 266
  • 294
  • I see, thats because of the AnyObject bit. If you look in the docs it says that node.children returns [AnyObject] (which will always be SKNodes apparently). Its funny how it always succeeds if you cast it to [NSString], I guess thats because AnyObject also covers NSString objects too. – fuzzygoat Nov 10 '14 at 16:05
  • It only succeeds when you cast it to `[NSString]` when it is empty. If there were any `SKNode`s in the array, the cast would not happen. – vacawama Nov 10 '14 at 16:07
  • yup perfect, I get it, I was forgetting about the fact that it can empty. Much appreciated Sir, thank you for your time. – fuzzygoat Nov 10 '14 at 16:13