代码之家  ›  专栏  ›  技术社区  ›  Duncan C

这是Swift 4编译器错误吗?

  •  0
  • Duncan C  · 技术社区  · 7 年前

    我写了一个小游戏来演示如何对数组坐标进行排序,以找到最接近的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编译器的典型特征,但代码似乎应该编译。我错过了什么?

    1 回复  |  直到 7 年前
        1
  •  2
  •   vadian    7 年前

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

    • 带注释的类型为 Array<CoordStruct>
    • prefix 退货 ArraySlice<CoordStruct>

    如果将行更改为

    let structs : ArraySlice<CoordStruct> = points.map { ...