Swift相当于Ruby的“each_cons”

时间:2016-09-28 19:41:15

标签: arrays ruby swift enumerator equivalent

红宝石

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")]

如何使这个快速代码更短或更简单?

2 个答案:

答案 0 :(得分:6)

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")]

答案 1 :(得分: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
            }
        }