【问题标题】:Is this a Swift 4 compiler error?这是 Swift 4 编译器错误吗?
【发布时间】:2018-03-23 13:16:33
【问题描述】:

我写了一个小操场来演示如何对数组坐标进行排序以找到最接近的 5 个。我使用高阶函数,将坐标映射到一个也包含距离的结构,对其进行排序,然后选择前 5 个项目。但是,我不能将前 5 名作为同一个复合语句的一部分进行最后的选择。

下面是代码:

    import Foundation
    import CoreLocation

    let currentLatitide = 19.1553902
    let currentLongitude = 72.8528602
    struct CoordStruct: CustomStringConvertible {
        let coord: CLLocationCoordinate2D
        let distance: Double

        var description: String {
            return "lat: " + String(format: "%.4f",coord.latitude) +
                ", long: " + String(format: "%.4f",coord.longitude) + ", distance: " + distance.description
        }
    }

    let location = CLLocation(latitude: currentLatitide, longitude: currentLongitude)

     let points =   [[19.5,71.0],[18.5,72.0],[19.15,72.85],[19.1,75.0],[19.2,70.0],[19.3,70.0],[19.4,70.0],[19.6,70.0],[19.7,70.2],[19.9,70.3],[25,62.0],[24.5,73.4],[23.5,65.0],[21.5,68.0],[20.5,69.0]]

    let structs: [CoordStruct] = points.map //This is where the error shows up.
        {
        let thisCoord = CLLocationCoordinate2D(latitude: $0[0], longitude: $0[1])
        let thisLocation = CLLocation(latitude:$0[0], longitude: $0[1])
        let distance = location.distance(from: thisLocation)
        return CoordStruct(coord: thisCoord, distance: distance)
        }
        .sorted { $0.distance < $1.distance }
        //----------------------------------
        .prefix(5)  //This won't compile
        //----------------------------------
    let first5Structs = structs.prefix(5)


    first5Structs.forEach { print($0) }

let test = points.map { $0[1] }
    .sorted { $0 < $1 }
    .prefix(5)

print(test)

请参阅标记为//This won't compile 的行。由于未注释该行,编译器在引用 map 语句时说“对成员 'map' 的模糊引用”。如果我注释掉有问题的行并在单独的行上做一个前缀,编译器会很高兴。错误消息毫无意义,这似乎是 Swift 编译器的典型特征,但代码似乎应该编译。我错过了什么?

【问题讨论】:

标签: swift compiler-errors higher-order-functions


【解决方案1】:

这个错误有点误导,这个问题是由返回类型不匹配引起的。

  • 注解类型为Array&lt;CoordStruct&gt;
  • prefix 返回ArraySlice&lt;CoordStruct&gt;

如果您将行更改为

,它将编译
let structs : ArraySlice<CoordStruct> = points.map { ...

【讨论】:

  • 另一种选择是省略类型注释,并使闭包类型显式:let structs = points.map{ point -&gt; CoordStruct in ...} ...
  • 谢谢!现在你解释它是有道理的。我希望 Swift 错误不要那么迟钝!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-24
  • 1970-01-01
  • 1970-01-01
  • 2011-05-29
  • 1970-01-01
  • 2015-01-31
相关资源
最近更新 更多