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)
}
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)
}
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])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.