gpt4 book ai didi

Swift 相当于 each_slice

转载 作者:搜寻专家 更新时间:2023-11-01 05:59:11 26 4
gpt4 key购买 nike

Swift中有没有类似Ruby的Enumerable#each_slice的东西?

ruby 示例:

arr = ["a", "b", "c", "d"]
arr.each_slice(2) {|s1, s2| puts s1 + s2 }

输出:

ab
cd

最佳答案

作为对 How to implement Haskell's splitEvery in Swift? 中代码的小修改, 你可以定义一个数组扩展

extension Array {
func eachSlice<S>(nInEach: Int, transform: [T] -> S) -> [S] {
var result = [S]()
for from in stride(from: 0, to: self.count, by: nInEach) {
let to = advance(from, nInEach, self.count)
result.append(transform(Array(self[from ..< to])))
}
return result
}
}

然后将其用作

let arr = ["a", "b", "c", "d"]
arr.eachSlice(2) { println("".join($0)) }

输出:

abcd

Another example:

let iarr = [1, 2, 3, 4, 5, 6, 7]
let sliceSums = iarr.eachSlice(3) {
reduce($0, 0) { $0 + $1 } // sum of slice elements
}
println(sliceSums)
// [6, 15, 7]

Swift 3 更新:

extension Array {
func eachSlice<S>(_ nInEach: Int, transform: (ArraySlice<Element>) -> S) -> [S] {
var result = [S]()
var from = startIndex
while from != endIndex {
let to = indices.index(from, offsetBy: nInEach, limitedBy: endIndex) ?? endIndex
result.append(transform(self[from ..< to]))
from = to
}
return result
}
}

let iarr = [1, 2, 3, 4, 5, 6, 7]
let sliceSums = iarr.eachSlice(3) { $0.reduce(0, +) }
print(sliceSums) // [6, 15, 7]

关于Swift 相当于 each_slice,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27984914/

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