在Swift中的Array中存储不同类型的值

Boo*_*oon 14 swift

在Swift编程语言中,它说"一个数组在一个有序列表中存储多个相同类型的值." 但我发现你可以在数组中存储多种类型的值.描述不正确吗?

例如

var test = ["a", "b", true, "hi", 1]
Run Code Online (Sandbox Code Playgroud)

Bry*_*hen 21

来自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>
Run Code Online (Sandbox Code Playgroud)

你可以看到testNSArray,这是一种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'
Run Code Online (Sandbox Code Playgroud)
 var test:Array = ["a", "b", true, "hi", 1]
<REPL>:4:18: error: cannot convert the expression's type 'Array' to type 'ExtendedGraphemeClusterLiteralConvertible'
Run Code Online (Sandbox Code Playgroud)

但你可以做到这一点

var test : Any[] = ["a", "b", true, "hi", 1]
Run Code Online (Sandbox Code Playgroud)

因为它们有一个共同的类型,即Any.


注意:AnyObject[]如果没有,将无法运作import Foundation.

var test:AnyObject[] = ["a", "b", true, "hi", 1]
<REPL>:2:24: error: type 'Bool' does not conform to protocol 'AnyObject'
Run Code Online (Sandbox Code Playgroud)

  • @BryanChen:也许这个Any []现在是[Any] (2认同)

Gor*_*ilt 6

要使用任意类型初始化Array,只需使用 var arbitraryArray = [Any]()