我收到此错误并且是Swift的新手。我想取一个数组的最后5个点> = 5,并将这5个点作为数组参数传递给函数。我怎样才能实现这一目标并克服这个错误?
无法将'ArraySlice'类型的值转换为预期的参数类型'[CGPoint]'
if (self.points?.count >= 5) {
let lastFivePoints = self.points![(self.points!.count-5)..<self.points!.count]
let angle = VectorCalculator.angleWithArrayOfPoints(lastFivePoints)
}
答案 0 :(得分:23)
您需要使用方法ArraySlice
Array
转换为Array(Slice<Type>)
if (self.points?.count >= 5) {
let lastFivePoints = Array(self.points![(self.points!.count-5)..<self.points!.count])
let angle = VectorCalculator.angleWithArrayOfPoints(lastFivePoints)
}
答案 1 :(得分:1)
您可以使用返回ArraySlice的前缀(upTo end:Self.Index)方法代替范围运算符,这样可以缩短代码。方法的定义:该方法从集合的开始返回一个子序列,但不包括指定的位置(索引)。
if (self.points?.count >= 5) {
let lastFivePoints = Array<CGPoint>(self.points?.prefix(upTo:5)) as [AnyObject]
let angle = VectorCalculator.angleWithArrayOfPoints(lastFivePoints)
}
// You can also do this
let lastFivePoints = Array<CGPoint>(self.points?[0...4])
答案 2 :(得分:1)