swift中,想要初始化一个指定个数的某个类型的数组,比如:
var uniqueRandomArr:[Int] = [Int](arrCount)
根据代码提示:
Missing argument label arrayLiterral in call
所以修改为:
var uniqueRandomArr:[Int] = [Int](arrayLiteral: arrCount)
但是最后调试时候才知道,原来上述的写法,实际上是:
只有单个元素,元素的初始化值是arrCount而已
而不是,初始化了一个包含arrCount个元素的数组
把:
- var someInts = [Int]() - print("someInts is of type [Int] with \(someInts.count) items.") - // prints "someInts is of type [Int] with 0 items." - var threeDoubles = [Double](count: 3, repeatedValue: 0.0) - // threeDoubles is of type [Double], and equals [0.0, 0.0, 0.0]
改为:
let invalidRandomNum = upper + 1 //var uniqueRandomArr:[Int] = [Int](arrayLiteral: arrCount) var uniqueRandomArr:[Int] = [Int](count: arrCount, repeatedValue: invalidRandomNum)
才可以。
此处的:
var someArr = [SomeType](count: yourArrayCount, repeatedValue: theDefaultValue)
中的SomeType可以是:
Int
Color
String
等等类型
当然,对应的theDefaultValue也是对应的值,比如:
var fourIntArr = [Int](count: 4, repeatedValue: 1) var fiveColorArr = [UIColor](count: 5, repeatedValue: UIColor.clearColor())
对应的[SomeType]只是个语法糖,完整写法是:Array<SomeType>
举例:
var uniqueHeaderColorArr:[UIColor] = Array(count: uniqueArrCount, repeatedValue: UIColor.clearColor())
转载请注明:在路上 » [已解决]swift初始化一个指定数量元素的数组