您可以創建一個二維數組,然後用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]
您需要將count參數類型更改爲Int,以將其用作從Uint到Int的索引或脅迫self.init([Array](count:Int(count),repeatedValue:repeatedValues).flatMap {$ 0})' –
啊,是的,事實證明,當我測試它時,我使用的代碼略微不同於我在這裏發佈的代碼。我改變它以更好地匹配原始的'init'方法。 – ColGraff