来自REPL
xcrun swift 1> import Foundation 2> var test = ["a", "b", true, "hi", 1]test: __NSArrayI = @"5 objects" { [0] = "a" [1] = "b" [2] = [3] = "hi" [4] = (long)1} 3>您可以看到的
test是
NSArray,这是
AnyObject[]或
NSObject[]
发生的事情是
Foundation提供了将数字和布尔值转换为的能力
NSNumber。需要编译代码时,编译器将执行转换。
因此,它们现在具有的通用类型,
NSObject因此可以推断为
NSArray
没有,您的代码将无法在REPL中编译
import Foundation。
var test = ["a", "b", true, "hi", 1]<REPL>:1:12: error: cannot convert the expression's type 'Array' to type 'ArrayLiteralConvertible'
var test:Array = ["a", "b", true, "hi", 1]<REPL>:4:18: error: cannot convert the expression's type 'Array' to type 'ExtendedGraphemeClusterLiteralConvertible'
但是你可以做到
var test : Any[] = ["a", "b", true, "hi", 1]
因为它们具有通用类型,即
Any。
注意:
AnyObject[]不能使用
import Foundation。
var test:AnyObject[] = ["a", "b", true, "hi", 1]<REPL>:2:24: error: type 'Bool' does not conform to protocol 'AnyObject'



