jjatie jjatie - 1 year ago 128
Swift Question

Use map to access next element in array

I want to transform an array of points into an array of lines like so:

let lines = points.map { $1 - $0 }

I get the error

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

I understand why I am getting this, but I could have sworn I'd seen sample code on SO using multiple arguments in a map closure. Is there a similar function I'm not finding that can do this?

Answer Source

My interpretation

Given an array of some CGPoint(s)

// pseudocode 
points = [a, b, c]

your want as output a list of segments

// 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: Thank your for the suggestion!


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download