问题
Consider the code:
struct S {
var f : Int64 = 0
}
...
let coder : NSCoder = someCoder ...
let a : [Int] = []
coder.encodeObject(a) // compiles
let b : [Int64] = []
coder.encodeObject(b) // doesn't compile: not AnyObject
let s : [S] = []
coder.encodeObject(s) // doesn't compile: not AnyObject
Note that Int is defined as a struct.
So [Int] is object, but [Int64] is not and neither is my array of simple structures.
What is special about Int?
回答1:
If you import Foundation (which you must be, because you reference NSCoder) then [Int] is implicitly bridged to NSArray because Int is implicitly bridged to NSNumber. Int64 and your non-objc structs are not implicitly bridged to ObjC types, so arrays of those are not bridged to NSArray.
回答2:
Int is bridged (as are UInt and Float and Double, as well as Bool). This means that they are wrapped up in an NSNumber for you, automatically, when you cast to AnyObject, and vice versa.
Other numeric types, alas, are not.
In turn, you also get to take advantage of array-casting syntactic sugar. An NSArray must consist of Objective-C objects, such as NSNumber. When you start with a Swift array, instead of having to wrap the elements up in an NSNumber yourself, as you do with an array of Int64, they are wrapped for you when you cast/bridge a Swift array to an NSArray.
回答3:
If Foundation framework is imported, Int (unlike Int64) is implicitly bridged to NSNumber which conforms to AnyObject
来源:https://stackoverflow.com/questions/35417438/why-is-a-swift-arrayint-compatible-with-anyobject