在Swift中重复数组 [英] Repeating array in Swift
问题描述
在Python中,我可以创建一个重复列表,如下所示:
In Python I can create a repeating list like this:
>>> [1,2,3]*3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
在Swift中有一种简洁的方法吗?
Is there a concise way to do this in Swift?
我能做的最好的事情是:
The best I can do is:
1> var r = [Int]()
r: [Int] = 0 values
2> for i in 1...3 {
3. r += [1,2,3]
4. }
5> print(r)
[1, 2, 3, 1, 2, 3, 1, 2, 3]
推荐答案
您可以创建2D数组,然后使用flatMap
将其转换为1D数组:
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}
这是一个扩展,它添加了一个init方法和一个重复方法,该方法采用了一个数组,这使它更简洁:
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:)‛
改为使用:
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)
或类似名称,则可以避免这种歧义.
This ambiguity can be avoided if you change the method signature to init(repeatingContentsOf: [Element], count: Int)
or similar.
这篇关于在Swift中重复数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!