Ale*_*ica 7 arrays functional-programming immutability swift
我遇到了一个需要成对迭代数组的问题.最好的方法是什么?或者,作为替代方案,将数组转换为数组对的最佳方法是什么(然后可以正常迭代)?
这是我得到的最好的.它需要output是一个var,它并不是真的很漂亮.有没有更好的办法?
let input = [1, 2, 3, 4, 5, 6]
var output = [(Int, Int)]()
for i in stride(from: 0, to: input.count - 1, by: 2) {
output.append((input[i], input[i+1]))
}
print(output) // [(1, 2), (3, 4), (5, 6)]
// let desiredOutput = [(1, 2), (3, 4), (5, 6)]
// print(desiredOutput)
Run Code Online (Sandbox Code Playgroud)
Mar*_*n R 21
您可以映射步幅而不是迭代它,这允许将结果作为常量获取:
let input = [1, 2, 3, 4, 5, 6]
let output = stride(from: 0, to: input.count - 1, by: 2).map {
(input[$0], input[$0+1])
}
print(output) // [(1, 2), (3, 4), (5, 6)]
Run Code Online (Sandbox Code Playgroud)
如果您只需要迭代对并且给定的数组很大,那么避免使用延迟映射创建中间数组可能是有利的:
for (left, right) in stride(from: 0, to: input.count - 1, by: 2)
.lazy
.map( { (input[$0], input[$0+1]) } ) {
print(left, right)
}
Run Code Online (Sandbox Code Playgroud)
现在可以作为
Sequence.chunks(ofCount: 2)包装的swift-algorithms
for chunk in input.chunks(ofCount: 2) {
print(chunk)
}
Run Code Online (Sandbox Code Playgroud)
我不认为这比 Martin R 更好,但似乎 OP 需要其他东西......
struct PairIterator<C: IteratorProtocol>: IteratorProtocol {
private var baseIterator: C
init(_ iterator: C) {
baseIterator = iterator
}
mutating func next() -> (C.Element, C.Element)? {
if let left = baseIterator.next(), let right = baseIterator.next() {
return (left, right)
}
return nil
}
}
extension Sequence {
var pairs: AnySequence<(Self.Iterator.Element,Self.Iterator.Element)> {
return AnySequence({PairIterator(self.makeIterator())})
}
}
input.pairs.forEach{ print($0) }
let output = input.pairs.map{$0}
print(output) //->[(1, 2), (3, 4), (5, 6)]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3030 次 |
| 最近记录: |