我想将一个点数组转换为一个行数组,如下所示:
domain.com/1
我收到错误
Contextual closure type '(Point) -> _' expects 1 argument, but 2 were used in closure body
我理解为什么我会这样做,但我可以发誓我在地图闭包中使用多个参数在SO上看到示例代码。是否有类似的功能我没有发现可以做到这一点?
答案 0 :(得分:4)
给定一些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))]
答案 1 :(得分: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]]
优点是可以定义线中的点数