Swift error: cannot convert value of type ArraySlice to expected argument type

I get this error and new to Swift. I want to take the last 5 points of the array> = 5 and pass these 5 points as an argument to the array of the function. How can I achieve this and overcome this error?

Cannot convert value of type "ArraySlice" to the 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) } 
+7
arrays swift
source share
3 answers

You need to convert ArraySlice to Array using the Array(Slice<Type>) 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) } 
+12
source share

Instead of a range operator, you can use the prefix method (upTo end: Self.Index), which returns an ArraySlice, which makes your code shorter. Method definition: the method returns a subsequence from the beginning of the collection 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]) 
+1
source share

I tried using Array(lastFivePoints) but I got an error

The type of expression is ambiguous without additional context.

enter image description here

I have finished work:

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

where T is the CGPoint content class for this example

0
source share

All Articles