您可以创建一个二维数组,然后使用flatMap 将其变成一维数组:
let array = [Int](repeating: [1,2,3], count: 3).flatMap{$0}
这是一个扩展,它添加了一个 init 方法和一个重复方法,该方法采用一个数组,这使得它更简洁:
extension Array {
init(repeating: [Element], count: Int) {
self.init([[Element]](repeating: repeating, count: count).flatMap{$0})
}
func repeated(count: Int) -> [Element] {
return [Element](repeating: self, count: count)
}
}
let array = [1,2,3].repeated(count: 3) // => [1, 2, 3, 1, 2, 3, 1, 2, 3]
请注意,使用新的初始化程序,如果您在没有提供预期类型的情况下使用它,您可能会得到一个模棱两可的方法调用:
let array = Array(repeating: [1,2,3], count: 3) // Error: Ambiguous use of ‛init(repeating:count:)‛
改用:
let array = [Int](repeating: [1,2,3], count: 3) // => [1, 2, 3, 1, 2, 3, 1, 2, 3]
或
let array:[Int] = Array(repeating: [1,2,3], count: 3) // => [1, 2, 3, 1, 2, 3, 1, 2, 3]
如果您将方法签名更改为 init(repeatingContentsOf: [Element], count: Int) 或类似名称,则可以避免这种歧义。