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

半腔热情 提交于 2019-12-02 12:23:02

问题


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?


回答1:


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].




回答2:


As usual, in writing this out, it makes sense. It's literally saying, that if cardB matched cardC, use an index of [1] (cardC), if not, use an index of [0] (cardB)

So,

cardA.contents = cardB.contents // if does NOT match
cardA.contents = cardC.contents // if matches

(based on the index).

Duh.. Sorry for a silly question...



来源:https://stackoverflow.com/questions/19868062/what-does-a-square-bracketed-index-after-an-nsarray-mean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!