Objective-C id as Swift Any
In Swift 3, the
id
type in Objective-C now maps to theAny
type 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 ofAny
type. For hashed containers, such asDictionary
andSet
, there’s a new typeAnyHashable
that can hold a value of any type conforming to the SwiftHashable
protocol.[…]
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
, orSet
withAnyObject
orNSObject
elements for this purpose, relying on implicit bridging conversions to handle value types[…] Swift now imports Cocoa APIs as accepting collections ofAny
and/orAnyHashable
, so we can change the collection type to use[AnyHashable: Any]
instead of[NSObject: AnyObject]
orNSDictionary
, without changing any other code.[…]
Any
does 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.