Any, AnyObject in Swift
Any
and AnyObject
AnyObject
is a reserved type in Swift to represent an instance of some class.
It plays a flexible role as a bridge between Objective-C because in Cocoa framework, the id
pointer address is core in Cocoa.
However, usage of AnyObject
in Swift is pretty cumbersome because AnyObject
always represents optional in Swift and we have to extract it’s value as we need like the following. The whole class
types in Swift implicitly conform AnyObject
protocol includes nothing inherently.
func someMethod() -> AnyObject? {
// ...
// result is an `AnyObject?` value, which is equivalent to `id`.
return result
}
let anyObject: AnyObject? = SomeClass.someMethod()
if let someInstance = anyObject as? SomeRealClass {
// ...
// Now, `someInstance` is `SomeRealClass` type. Use it directly.
someInstance.funcOfSomeRealClass()
}
I figured out the need of Any
type is from here. The Any
type in Swift is not only covering class instance type but struct or enum type. We could use Any
to represent literally any type of swift but optional. You must append suffix ?
to Any
for covering optional types.
Implicit type conversion to Objective-C
The more interesting was how the swift compiler and Foundation
framework convert primitive Swift types into Cocoa types like String -> NSString
.
Let me show the following example.
import UIKit
let swiftInt: Int = 1
let swiftString: String = "miao"
var array: [AnyObject] = []
array.append(swiftInt)
array.append(swiftString)
I’d import Foundation
implicitly by adding import UIKit
makes Swift Array
of AnyObject
appends Int
or String
(value type) into AnyObject
because Foundation
converts Swift primitive value types into Cocoa class types(NSNumber
, NSString
).
By removing UIKit
, the Swift compiler generate error.
Comments