【问题标题】:Swift equivalent of Ruby's "each_cons"Swift 相当于 Ruby 的 "each_cons"
【发布时间】:2017-02-06 22:53:04
【问题描述】:

红宝石

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 中的相同代码,但没有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 代码更短或更简单?

【问题讨论】:

标签: arrays ruby swift enumerator equivalent


【解决方案1】:
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")]

【讨论】:

  • 非常优雅的解决方案。谢谢凯文
  • 我很高兴有人对此有所考虑。我们可以概括一下,这样我们就不必对2each_cons(2) 进行硬编码吗?
  • 但是,Swift 没有zip 的通用版本:这仅适用于配对。
  • @JoshCaswell 正确。我有一个更通用的解决方案,但它的效率非常低。
【解决方案2】:

这是我想出的通用解决方案,但它似乎效率极低。要实现each_cons(n),请将我的clump 设置为n

        let arr = [1,2,3,4,5,6,7,8]
        let clump = 2
        let cons : [[Int]] = arr.reduce([[Int]]()) {
            memo, cur in
            var memo = memo
            if memo.count == 0 {
                return [[cur]]
            }
            if memo.count < arr.count - clump + 1 {
                memo.append([])
            }
            return memo.map {
                if $0.count == clump {
                    return $0
                }
                var arr = $0
                arr.append(cur)
                return arr
            }
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-18
    • 2021-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-07
    • 2020-02-16
    • 2012-10-05
    相关资源
    最近更新 更多