Repeating array in Swift

后端 未结 4 392
滥情空心
滥情空心 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:09

    You can use modulo operations for index calculations of your base collection and functional programming for this:

    let base = [1, 2, 3]
    let n = 3 //number of repetitions
    let r = (0..<(n*base.count)).map{base[$0%base.count]}
    

    You can create a custom overload for the * operator, which accepts an array on the left and an integer on the right side.

    func * (left: [T], right: Int) -> [T] {
        return (0..<(right*left.count)).map{left[$0%left.count]}
    }
    

    You can then use your function just like in python:

    [1, 2, 3] * 3
    // will evaluate to [1, 2, 3, 1, 2, 3, 1, 2, 3]
    

提交回复
热议问题