Search code examples
objective-ccocoa-touchindexingnsarrayobjective-c-literals

What does a square-bracketed index after an NSArray mean?


Going through iTunes U Developing iOS 7 Apps for iPhone and iPad and in Lecture 3 slides, on page 120, there's a Quiz question that asks what the following line of code does. Frankly, I'm a bit stumped, and hoped someone could break it down.

cardA.contents = @[cardB.contents,cardC.contents][[cardB match:@[cardC]] ? 1 : 0];

So, I get the first part, cardA.contents = a new array with cardB.contents and cardC.contents in the array. But, next comes (I guess??) an index that returns either 1 or 0 depending if cardB matches an array that includes cardC.

Here's what I don't "get", and maybe it's just a syntax issue.... is what this does?

How is

cardA.contents = @[cardB.contents,cardC.contents][0];

or

cardA.contents = @[cardB.contents,cardC.contents][1];

Valid? Or, did I miss something?


Solution

  • Your understanding is completely correct; you're just missing one bit of syntax. Subscripted access of NSArrays with the array[index] form is part of the "collection literals" feature introduced by Clang a little while back.

    It's transformed by the compiler into a call to [array objectAtIndexedSubscript:index].