Subscripting

Clang introduces container access using standard subscripting, via square brackets. In other words, you can now access an NSArray just as you would a C array. You can do the same with an NSDictionary, although indexed by key rather than number. Here are a couple examples of doing so, using the array and dictionary declared earlier:

NSLog(@"%@", array[1]); // @"two" NSLog(@"%@", dictionary[@"key 2"]); // @"value 2"

But you’re not just limited to value look-ups. Using this new syntax, you can also perform assignments for mutable instances. Here’s how you might use the new subscripting features in simple assignments:

mutableArray[0] = @"first!"; mutableDictionary[@"some key"] ...

Get The Core iOS Developer’s Cookbook, Fifth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.