今天研究了下数组array
的初始化,刚开始想初始化一个由array
组成的array
,结果总是报错。
初始化一个
Int
数组
var intArray = [Int]()
intArray.append(2)
intArray.append(3)
print(intArray)
可以正常编译
[2, 3]
但是,当尝试初始化一个由数组组成的数组,会报错:
var array = [Array]()
array.append([2])
print(array)
ListSubArray.swift:36:19: error: generic parameter 'Element' could not be inferred
var array = [Array]()
^
Swift.Array:282:15: note: 'Element' declared as parameter to type 'Array'
public struct Array<Element> : RandomAccessCollection, MutableCollection, _DestructorSafeContainer {
^
后来尝试,只能初始化Any
类型的数组才能实现:
var array = [Any]()
array.append([2])
print(array)
[[2]]
对于数组初始化,官方文档中并没有提到不能初始化Array
类型的Array
,但是也没有给出类似示范。
而对于明确类型的数组初始化,网上的初始化例子也大都是:
var stringArray = [String]()
stringArray.append("1")
stringArray.append("2")
stringArray.append("3")
print("stringArray is \(stringArray)")
var stringArray2: [String] = ["1", "2"]
print("stringArray2 is \(stringArray2)")
var stringArray3: Array<String> = []
stringArray3.append("1")
stringArray3.append("2")
print("stringArray3 is \(stringArray3)")
var stringArray4: [String] = []
stringArray4.append("1")
stringArray4.append("2")
print("stringArray4 is \(stringArray4)")
结果如下:
stringArray is ["1", "2", "3"]
stringArray2 is ["1", "2"]
stringArray3 is ["1", "2"]
stringArray4 is ["1", "2"]
官方标准初始化空数组例子:
var someInts = [Int]()
print("someInts is of type [Int] with \(someInts.count) items.")
// Prints "someInts is of type [Int] with 0 items.
Excerpt From: Apple Inc. “The Swift Programming Language (Swift 3 beta).” iBooks.
结果为:
someInts is of type [Int] with 0 items.
如果是初始化一个数组组成的数组,也可以尝试:
let a = [1, 2, 3]
let b = [2, 3, 1]
var c = [a, b]
print(c)
可以顺利编译,结果如下:
[[1, 2, 3], [2, 3, 1]]
但是空数组的初始化,就遇到问题了。
let a = [1, 2, 3]
let b = [2, 3, 1]
var c = [a, b]
print(c)
var d = [Any]()
d.append(a)
d.append(b)
print(d)
只有设置为Any
才能编译,如下:
[[1, 2, 3], [2, 3, 1]]
[[1, 2, 3], [2, 3, 1]]
网友评论