I read inline documentation of Swift and I am bit confused.
1) Any
is a protocol that all types implicitly conform.
2) 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".
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.
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)
class Test {
static func test() {
let anyObjectsValues: [AnyObject] = [1, "Two", 3, "Four"] as [AnyObject]
anyObjectsValues.forEach { (value) in
switch value {
case is Int:
print("\(value) is an Int!")
case is String:
print("\(value) is a String!")
default:
print("\(value) is some other type!")
}
}
}
}
I have not imported UIKit or Foundation frameworks. Why compiler is not giving any error? Even it printing the result.
Output:
1 is an Int!
Two is a String!
3 is an Int!
Four is a String!
Does anybody have an idea?