Objective-C id as Swift Any
In Swift 3, the
idtype in Objective-C now maps to theAnytype in Swift, which describes a value of any type, whether a class, enum, struct, or any other Swift type. This change makes Objective-C APIs more flexible in Swift, because Swift-defined value types can be passed to Objective-C APIs and extracted as Swift types, eliminating the need for manual “box” types. These benefits also extend to collections: Objective-C collection typesNSArray,NSDictionary, andNSSet, which previously only accepted elements ofAnyObject, now can hold elements ofAnytype. For hashed containers, such asDictionaryandSet, there’s a new typeAnyHashablethat can hold a value of any type conforming to the SwiftHashableprotocol.[…]
Property lists, JSON, and user info dictionaries are common in Cocoa, and Cocoa natively represents these as untyped collections. In Swift 2, it was necessary to build
Array,Dictionary, orSetwithAnyObjectorNSObjectelements for this purpose, relying on implicit bridging conversions to handle value types[…] Swift now imports Cocoa APIs as accepting collections ofAnyand/orAnyHashable, so we can change the collection type to use[AnyHashable: Any]instead of[NSObject: AnyObject]orNSDictionary, without changing any other code.[…]
Anydoes not have the same magic method lookup behavior asAnyObject. This may break some Swift 2 code that looked up a property or sent a message to an untyped Objective-C object.