在Swift编程语言中,它说“一个数组在一个有序列表中存储多个相同类型的值.”但我发现你可以在数组中存储多种类型的值.描述不正确吗?
例如
- var test = ["a","b",true,"hi",1]
来自REPL
- xcrun swift
- 1> import Foundation
- 2> var test = ["a",1]
- test: __NSArrayI = @"5 objects" {
- [0] = "a"
- [1] = "b"
- [2] =
- [3] = "hi"
- [4] = (long)1
- }
- 3>
你可以看到测试是NSArray,它是一种AnyObject []或NSObject []
发生的事情是Foundation提供了将数字和布尔值转换为NSNumber的能力.只要需要编译器编译,编译器就会执行转换.
所以他们现在有了共同类型的NSObject,因此推断为NSArray
没有import Foundation,您的代码不会在REPL中编译.
- var test = ["a",1]
- <REPL>:1:12: error: cannot convert the expression's type 'Array' to type 'ArrayLiteralConvertible'
- var test:Array = ["a",1]
- <REPL>:4:18: error: cannot convert the expression's type 'Array' to type 'ExtendedGraphemeClusterLiteralConvertible'
但你可以做到这一点
- var test : Any[] = ["a",1]
因为它们有一个共同的类型,即Any.
注意:如果没有import Foundation,AnyObject []将无效.
- var test:AnyObject[] = ["a",1]
- <REPL>:2:24: error: type 'Bool' does not conform to protocol 'AnyObject'