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

时间:2016-01-27 04:15:12

标签: arrays swift

我收到此错误并且是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)
}

3 个答案:

答案 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)

我尝试使用Array(lastFivePoints),但我收到了错误

  

如果没有更多的上下文,表达的类型是不明确的

enter image description here

我最终做了:

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

其中T是此示例的内容类CGPoint