使用 map 访问数组中的下一个元素

Use map to access next element in array

我想像这样将一个点数组转换成一个线数组:

let lines = points.map {  - [=10=] }

我收到错误

Contextual closure type '(Point) -> _' expects 1 argument, but 2 were used in closure body

我明白为什么我会得到这个,但我可以发誓我已经看到了在 map 闭包中使用多个参数的 SO 示例代码。是否有类似的功能我没有找到可以做到这一点?

我的解读

给定一些 CGPoint(s)

的数组
// pseudocode 
points = [a, b, c]

你想要输出一个段列表

// pseudocode
segments = [(a, b), (b, c)]

实施

struct Segment {
    let from: CGPoint
    let to: CGPoint
}

let points = [CGPointZero, CGPoint(x: 1, y: 1), CGPoint(x: 2, y: 2)]

let segments = zip(points, points.dropFirst()).map(Segment.init)

@Martin R:感谢您的建议!

结果

[Segment(from: (0.0, 0.0), to: (1.0, 1.0)), Segment(from: (1.0, 1.0), to: (2.0, 2.0))]

另一种可能性是使用reduce。让我们

let arr = [1,2,3,4,5,6,7,8]
let n = 3 // number of points in the line
let l = arr.reduce([[]]) { (s, p) -> [[Int]] in
    var s = s
    if let l = s.last where l.count < n {
        var l = l
        l.append(p)
        s[s.endIndex - 1] = l
    } else {
        s.append([p])
    }
    return s
}
print(l) // [[1, 2, 3], [4, 5, 6], [7, 8]]

优点是可以定义直线上的点数