gpt4 book ai didi

arrays - 在 Swift 中重复数组

转载 作者:搜寻专家 更新时间:2023-10-31 21:50:06 24 4
gpt4 key购买 nike

在 Python 中,我可以像这样创建一个重复列表:

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

在 Swift 中有没有一种简洁的方法可以做到这一点?

我能做的最好的是:

  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]

最佳答案

您可以创建一个二维数组,然后使用 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) 或类似的,则可以避免这种歧义。

关于arrays - 在 Swift 中重复数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37095943/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com