In Swift, how is it that AnyObject
supports subscripts, even for types that are't subscriptable? Example:
let numbers: AnyObject = [11, 22, 33]
numbers[0] // returns 11
let prices: AnyObject = ["Bread": 3.49, "Pencil": 0.5]
prices["Bread"] // returns 3.49
let number: AnyObject = 5
number[0] // return nil
let number: AnyObject = Int(5)
number[0] // return nil
Yet if my number
is declared as Int
then it's a syntax error:
let number: Int = 5
number[0] // won't compile
Interestingly, Any
doesn't have subscript support.
It has to do with the bridging of types when assigning a value to an object of type
AnyObject
:Behind the scenes,
_SwiftDeferredNSArray.Type
,_NativeDictionaryStorageOwner<String, Double>.Type
, and__NSCFNumber.Type
must support subscripts whileInt.Type
does not.This is assuming you have imported Foundation. For an explanation with pure Swift types, see Cristik's answer.