Swift Error: Cannot convert value of type 'ArraySlice' to expected argument type

若如初见. 提交于 2019-12-08 14:35:44

问题


I'm getting this error and am new to Swift. I want to take the last 5 points of an array >= 5, and pass those 5 points as an array argument to a function. How can I achieve this and get past this error?

Cannot convert value of type 'ArraySlice' to expected argument type '[CGPoint]'

if (self.points?.count >= 5) {
    let lastFivePoints = self.points![(self.points!.count-5)..<self.points!.count]
    let angle = VectorCalculator.angleWithArrayOfPoints(lastFivePoints)
}

回答1:


You need to convert ArraySlice to Array using method 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)
}



回答2:


Instead of the range operator you can use prefix(upTo end: Self.Index) method that return ArraySlice which makes your code shorter. Method's definition: The method returns a subsequence from the start of the collection up to, but not including, the specified position (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]) 



回答3:


I tried using Array(lastFivePoints) but i got error

Type of expression is ambiguous without more context

I ended up doing:

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

where T is the content class CGPoint for this example



来源:https://stackoverflow.com/questions/35028784/swift-error-cannot-convert-value-of-type-arrayslice-to-expected-argument-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!