How does NSArray differ from Swift Array?
Main differences
- Semantics.
Arrayis a struct, a value type with copy-on-write;NSArrayis a class, a reference type. Immutability forNSArrayis at the class level (NSArrayvsNSMutableArray), forArrayat the variable level (letvsvar). - Typing.
Array<Element>is generic and holds any type, including structs and enums.NSArrayholds objects only (AnyObject); Swift structs get boxed when bridged (Int→NSNumber,String→NSString, your own struct →_SwiftValue). - Thread safety. Neither is thread-safe under mutation, but
Arrayas a value type is safe to read from several threads (no shared mutable state);NSMutableArrayis a shared object. - API.
NSArrayhas Foundation methods (firstObject,objectAtIndex, KVC/KVO,arrayController),Arrayhas theCollectionprotocols (map,filter,lazy, slices).
The rest of this answer, with code and interview follow-ups, is in the DevPrep app.
Read the full answer in DevPrep