Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

swift

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)
}
like image 383
chris P Avatar asked Jan 27 '16 04:01

chris P


3 Answers

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)
}
like image 83
deoKasuhal Avatar answered Oct 11 '22 14:10

deoKasuhal


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]) 
like image 31
Ohmy Avatar answered Oct 11 '22 16:10

Ohmy


I tried using Array(lastFivePoints) but i got error

Type of expression is ambiguous without more context

enter image description here

I ended up doing:

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

where T is the content class CGPoint for this example

like image 2
Ted Avatar answered Oct 11 '22 15:10

Ted