在这种情况下,容器数组的类型应该是[Any],以使其包含ints和ints数组。
let arr1 = [1,2,3] // by default, it should be of type [Int]
let arr2:[Any] = [4,5,6,arr1]
print(arr2) // [4, 5, 6, [1, 2, 3]]
请注意,Swift 是强类型的,默认情况下,数组必须是一个整数数组,-不像 Objective-C- 数组不能包含混合数据类型。
这就是为什么你应该Any 输入:
Any 可以表示任何类型的实例,包括函数
类型。
注意:
仅当您明确需要行为时才使用 Any 和 AnyObject
他们提供的能力。 具体一点总是更好的
您希望在代码中使用的类型。
访问元素:
默认情况下,从[Any]数组访问元素的类型应该是Any,例如:
let numberOne = arr2[0] // type of Any
let myArray = arr2[3] // type of Any
为了得到想要的数据类型,你应该cast使用as?操作符和可选绑定,如下:
if let oneInt = arr2[0] as? Int {
print("one is an Int and it equals to: \(oneInt)")
} else {
print("one is NOT ad Int")
}
// one is an Int and it equals to: 4
if let oneString = arr2[0] as? String {
print("one is an Int and it equals to: \(oneString)")
} else {
print("one is NOT ad Int")
}
// one is NOT ad Int
备注:如果类型不匹配,使用as!操作符会导致应用崩溃。
let oneInt = arr2[0] as! Int // works fine
let oneString = arr2[0] as! String // CRASH!
有关as 运算符的更多信息,您可能需要查看此Q&A 和Type Casting 文档。