Repeating array in Swift

后端 未结 4 424
滥情空心
滥情空心 2021-01-12 12:11

In Python I can create a repeating list like this:

>>> [1,2,3]*3
[1, 2, 3, 1, 2, 3, 1, 2, 3]

Is there a concise way to do this in

4条回答
  •  无人及你
    2021-01-12 13:04

    You can create a 2D array and then use flatMap to turn it into a 1D array:

    let array = [Int](repeating: [1,2,3], count: 3).flatMap{$0}
    

    Here's an extension that adds an init method and a repeating method that takes an array which makes this a bit cleaner:

    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]
    

    Note that with the new initializer you can get an ambiguous method call if you use it without providing the expected type:

    let array = Array(repeating: [1,2,3], count: 3) // Error: Ambiguous use of ‛init(repeating:count:)‛
    

    Use instead:

    let array = [Int](repeating: [1,2,3], count: 3) // => [1, 2, 3, 1, 2, 3, 1, 2, 3]
    

    or

    let array:[Int] = Array(repeating: [1,2,3], count: 3) // => [1, 2, 3, 1, 2, 3, 1, 2, 3]
    

    This ambiguity can be avoided if you change the method signature to init(repeatingContentsOf: [Element], count: Int) or similar.

提交回复
热议问题