Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Odd property declaration syntax containing angular brackets <>

I just downloaded FourInARow from 2015 WWDC sample code (https://developer.apple.com/sample-code/wwdc/2015/) and noticed an odd property declaration in file AAPLViewController.m

@property NSArray<NSMutableArray<CAShapeLayer *> *> *chipLayers;

What does it mean?

like image 464
imas145 Avatar asked Jun 09 '15 10:06

imas145


2 Answers

It is a new addition to Objective-C, called Lightweight Generics. It was introduced in iOS9 / OS X 10.11 in order to enhance interoperability between Swift and Objective-C. As the documentation says:

Objective-C declarations of NSArray, NSSet and NSDictionary types using lightweight generic parameterization are imported by Swift with information about the type of their contents preserved.

For example, consider the following Objective-C property declarations:

@property NSArray<NSDate *>* dates; 
@property NSSet<NSString *>* words; 
@property NSDictionary<KeyType: NSURL *, NSData *>* cachedData;

Here’s how Swift imports them:

var dates: [NSDate]
var words: Set<String> 
var cachedData: [NSURL: NSData]
like image 81
Michał Ciuba Avatar answered Sep 18 '22 00:09

Michał Ciuba


In addition to Michał Ciuba's answer:

Despite that the documentation (Lightweight Generics) doesn't seem to explicitly mention it, it's not just for Swift: this syntax does affect Objective-C. If you declare, say, a mutable array of CAShapeLayer*, then adding or accessing incompatible elements will produce compiler warnings. E.g.

NSMutableArray<CAShapeLayer*>* array = [NSMutableArray new];
[array addObject:[CATextLayer new]]; // warning
CATextLayer* layer = array[0]; // warning
CALayer* layer = array[0]; // OK, because CALayer is a superclass of CAShapeLayer
like image 22
mojuba Avatar answered Sep 18 '22 00:09

mojuba