【问题标题】:Swift Error: Cannot convert value of type 'ArraySlice' to expected argument typeSwift 错误:无法将“ArraySlice”类型的值转换为预期的参数类型
【发布时间】:2016-05-03 21:33:26
【问题描述】:

我遇到了这个错误,并且是 Swift 的新手。我想取数组的最后 5 个点 >= 5,并将这 5 个点作为数组参数传递给函数。我怎样才能做到这一点并克服这个错误?

无法将“ArraySlice”类型的值转换为预期的参数类型“[CGPoint]”

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

【问题讨论】:

标签: arrays swift


【解决方案1】:

您需要使用Array(Slice&lt;Type&gt;)方法将ArraySlice转换为Array

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

【讨论】:

  • 这不是通过实例化一个新的 Array 来否定 ArraySlice 的优势吗?导致另一个内存分配。
【解决方案2】:

您可以使用返回 ArraySlice 的 prefix(upTo end: Self.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】:

    我尝试使用Array(lastFivePoints),但出现错误

    没有更多上下文的表达类型是模棱两可的

    我最终做了:

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

    其中 T 是此示例的内容类 CGPoint

    【讨论】:

      猜你喜欢
      • 2017-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-16
      • 2020-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多