Is Float, Double, Int an AnyObject?
Because you have Foundation imported, Int
, Double
, and Float
get converted to NSNumber
when passed to a function taking an AnyObject
. Type String
gets converted to NSString
. This is done to make life easier when calling Cocoa and Cocoa Touch based interfaces. If you remove import UIKit
(or import Cocoa
for OS X), you will see:
error: argument type 'Int' does not conform to expected type 'AnyObject'
when you call
passAnyObject(a)
This implicit conversion of value types to objects is described here.
Update for Swift 3 (Xcode 8 beta 6):
Passing an Int
, Double
, String
, or Bool
to a parameter of type AnyObject
now results in an error such as Argument of type 'Int' does not conform to expected type 'AnyObject'.
With Swift 3, implicit type conversion has been removed. It is now necessary to cast Int
, Double
, String
and Bool
with as AnyObject
in order to pass it to a parameter of type AnyObject
:
let a = 1
passAnyObject(a as AnyObject)
Good find! UIKit
actually converts them to NSNumber
- also mentioned by @vacawama. The reason for this is, sometimes you're working with code that returns or uses AnyObject
, this object could then be cast (as!
) as an Int
or other "structs".