[英]Swift Error: Cannot convert value of type 'ArraySlice' to expected argument type
I'm getting this error and am new to Swift. 我收到了这个错误,并且是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.
我想取一个数组> = 5的最后5个点,并将这5个点作为数组参数传递给函数。 How can I achieve this and get past this error?
我怎样才能实现这个并克服这个错误?
Cannot convert value of type 'ArraySlice' to expected argument type '[CGPoint]' 无法将'ArraySlice'类型的值转换为预期的参数类型'[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>)
您需要使用方法
Array(Slice<Type>)
将ArraySlice
转换为Array
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. 您可以使用返回ArraySlice的前缀(upTo end:Self.Index)方法代替范围运算符,这样可以缩短代码。 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])
I tried using Array(lastFivePoints)
but i got error 我尝试使用
Array(lastFivePoints)
但我收到了错误
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 其中T是此示例的内容类CGPoint
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.