I read inline documentation of Swift and I am bit confused.
1) Any
is a protocol that all types implicitly conform.
2) AnyObject
is a protocol to which all classes implicitly conform.
3) Int
, Float
, Double
are structs
Here is a sample code:
import UIKit
func passAnyObject(param: AnyObject) {
print(param)
}
class MyClass {}
struct MyStruct {}
let a: Int = 1
let b = 2.0
let c = NSObject()
let d = MyClass()
let e = MyStruct()
passAnyObject(a)
passAnyObject(b)
passAnyObject(c)
passAnyObject(d)
//passAnyObject(e) // Argument type 'MyStruct' does not conform to expected type 'AnyObject'
if a is AnyObject { // b, d, e is also AnyObject
print("\(a.dynamicType) is AnyObject")
}
What I don't understand is why Int
, Double
, Float
are AnyObject
s? Why compiler doesn't say anything? Those types are declared as structs. Struct MyStruct
cannot be passed to the method on the top because it does not conform to AnyObject
.
Could you help me understand why Int
, Double
and Float
are AnyObject
or why compiler thinks they are?
AnyObject is a protocol that can represent an instance of any class type. It also has a more general counterpart, Any , which can represent any type at all (including structs and enums).
You use AnyObject when you need the flexibility of an untyped object or when you use bridged Objective-C methods and properties that return an untyped result. AnyObject can be used as the concrete type for an instance of any class, class type, or class-only protocol.
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)
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With