Alak Alak - 1 year ago 127
Swift Question

AnyObject and Any in Swift

I don't understand when to use AnyObject and when to user Any in Swift.

My case, I've a Dictionary

[String: ???]

??? : Can be Int, Double, Float, String, Array, Dictionary

someone can explain me the difference between Any and AnyObject
and witch one to use in my case.


Answer Source

AnyObject is only for reference types (classes), Any is for both value and reference types.

So you should go for [String: Any].

Type Casting for Any and AnyObject

Swift provides two special type aliases for working with non-specific types:

AnyObject can represent an instance of any class type. Any can represent an instance of any type at all, apart from function types.

NOTE: Use Any and AnyObject only when you explicitly need the behavior and capabilities they provide. It is always better to be specific about the types you expect to work with in your code.

From The Swift Programming Language:


Also note that when you work with Cocoa API, it's common to receive an Array of AnyObject, this is because Objective-C arrays are NOT typified. So you need to cast them to the array type you expect.


EDIT: (december 22, 2015)
On the last statement, note that this is changing with Swift 2.0 and Xcode 7.
Apple has introduced ‘Lightweight’ generics in Objective-C so lots of Cocoa APIs now already returns the correct type.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download