Swift错误:无法将类型为'ArraySlice'的值转换为预期的参数类型

44
我遇到了这个错误,不熟悉Swift。我想取数组中最后五个大于等于5的点,并将这些点作为数组参数传递给函数。我该如何实现这一过程并解决错误?
无法将类型为'ArraySlice'的值转换为期望的参数类型'[CGPoint]'。
if (self.points?.count >= 5) {
    let lastFivePoints = self.points![(self.points!.count-5)..<self.points!.count]
    let angle = VectorCalculator.angleWithArrayOfPoints(lastFivePoints)
}

18
尝试使用 Array(yourArraySlice)。该语句会将你的数组切片转换为新的数组。 - Leo Dabus
1
可能是如何从Swift 2.0获取子数组的重复问题。 - Eric Aya
3个回答

51
你需要使用方法 Array(Slice<Type>)ArraySlice 转换为 Array
if (self.points?.count >= 5) {
    let lastFivePoints = Array(self.points![(self.points!.count-5)..<self.points!.count])
    let angle = VectorCalculator.angleWithArrayOfPoints(lastFivePoints)
}

2
这难道不会抵消 ArraySlice 的优点,通过实例化新的 Array; 导致另一个内存分配。 - scord

4

你可以使用前缀(upTo end: Self.Index)方法替代范围运算符,该方法返回ArraySlice,使您的代码更短。方法的定义:该方法从集合的开头返回一个子序列,直到但不包括指定的位置(索引)。

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
我尝试使用Array(lastFivePoints),但是出现了错误。

没有更多上下文的情况下,表达式的类型不明确。

enter image description here

最终我做了这个:

let arr = lastFivePoints.map({ (x) -> T in
                            return x
                        })

在这个例子中,T 是 CGPoint 内容类。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接