gpt4 book ai didi

arrays - Swift 相当于 Ruby 的 "each_cons"

转载 作者:搜寻专家 更新时间:2023-10-30 22:32:41 25 4
gpt4 key购买 nike

ruby

Ruby 有 each_cons可以这样使用

class Pair
def initialize(left, right)
@left = left
@right = right
end
end
votes = ["a", "b", "c", "d"]
pairs = votes.each_cons(2).map { |vote| Pair.new(*vote) }
p pairs
# [#<Pair @left="a", @right="b">, #<Pair @left="b", @right="c">, #<Pair @left="c", @right="d">]

swift

swift 中的相同代码,但没有 each_cons 函数

struct Pair {
let left: String
let right: String
}
let votes = ["a", "b", "c", "d"]
var pairs = [Pair]()
for i in 1..<votes.count {
let left = votes[i-1]
let right = votes[i]
pairs.append(Pair(left: left, right: right))
}
print(pairs)
// [Pair(left: "a", right: "b"), Pair(left: "b", right: "c"), Pair(left: "c", right: "d")]

如何让这个 swift 代码更短或更简单?

最佳答案

zip(votes, votes.dropFirst())

这会产生一个元组序列。

例子

struct Pair {
let left: String
let right: String
}
let votes = ["a", "b", "c", "d"]
let pairs = zip(votes, votes.dropFirst()).map {
Pair(left: $0, right: $1)
}
print(pairs)
// [Pair(left: "a", right: "b"), Pair(left: "b", right: "c"), Pair(left: "c", right: "d")]

关于arrays - Swift 相当于 Ruby 的 "each_cons",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39756309/

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