This works only if you import Foundation
, as Swift is doing in that case some bridging to Objective-C
types - a NSArray
-like object in this case.
import Foundation
let numbers: AnyObject = [11, 22, 33] as AnyObject
type(of: numbers) //_SwiftDeferredNSArray.Type
If you don't import Foundation
, then you are not even allowed to make the assignment (because a Swift array is a struct and not an object).
let numbers: AnyObject = [11, 22, 33] // error: contextual type 'AnyObject' cannot be used with array literal
You can cast to Any
, though:
let numbers: Any = [11, 22, 33]
type(of: numbers) // Array<Int>.Type
Why does the import Foundation
does the trick? This is documented in the AnyObject
type description:
/// When used as a concrete type, all known `@objc` methods and
/// properties are available, as implicitly-unwrapped-optional methods
/// and properties respectively, on each instance of `AnyObject`. For
/// example:
///
/// class C {
/// @objc func getCValue() -> Int { return 42 }
/// }
///
/// // If x has a method @objc getValue()->Int, call it and
/// // return the result. Otherwise, return nil.
This means you can even call methods on your array that don't necessarily exist on NSArray
, but exists in the Objective-C
world, like for example:
numbers.lowercaseString // nil
and Swift will gracefully return you a nil
value instead of throwing you a nasty object does not recognises selector
exception, like it would happen in Objective-C. If this is good or bad, remains to debate :)
Update
The above seems to work only for properties, and property-like methods, if you try to use an Objective-C method, then you'll run into the unrecognized selector issue:
import Foundation
@objc class TestClass: NSObject {
@objc var someProperty: Int = 20
@objc func someMethod() {}
}
let numbers: AnyObject = [11, 22, 33] as AnyObject
numbers.lowercaseString // nil
numbers.someMethod // nil
numbers.someMethod() // unrecognized selector
numbers.stringByAppendingString("abc") // unrecognized selector
AnyObject
for an object whose proper type the compiler can infer and you - the developer - know exactly. Apple strongly discourages from using (such kind of) type annotations anyway. – PulidoNSJSONSerialization.JSONObjectWithData
returnsAnyObject
– Zoba