如何在Swift对象数组中找到具有最小属性值的对象?

时间:2017-03-24 18:21:21

标签: arrays swift min

我有Place类的以下Object Array:

class Place: NSObject {
    var distance:Double = Double()
    init(_ distance: Double) {
        self.distance = distance
    }
}


let places = [Place(1.5), Place(8.4), Place(4.5)]

我需要以最小距离获得地方。 我尝试使用

let leastDistancePlace = places.min { $0.distance > $1.distance }

根据this对类似问题的回答,但它给出了以下错误。

  

上下文闭包类型'(Place) - > _'期望1个参数,但是2个   用于封闭体

PS:

根据@robmayoff的回答,我在操场上尝试了以下内容,但我一直收到错误:

  

类型的值[Place] no member min

请查看此屏幕截图。 enter image description here

我的快速版本是:Apple Swift 2.2版(swiftlang-703.0.18.8 clang-703.0.31)

3 个答案:

答案 0 :(得分:3)

let leastDistancePlace = places.min { $0.distance < $1.distance }

let leastDistancePlace = places.min(by: { $0.distance < $1.distance })

示例:

:; xcrun swift
"crashlog" and "save_crashlog" command installed, use the "--help" option for detailed help
Welcome to Apple Swift version 3.0.2 (swiftlang-800.0.63 clang-800.0.42.1). Type :help for assistance.
  1>     class Place { 
  2.         var distance:Double = Double() 
  3.         init(_ distance: Double) { 
  4.             self.distance = distance 
  5.         } 
  6.     } 
  7.  
  8.  
  9.     let places = [Place(1.5), Place(8.4), Place(4.5)] 
 10.     let leastDistancePlace = places.min { $0.distance < $1.distance }
places: [Place] = 3 values {
  [0] = {
    distance = 1.5
  }
  [1] = {
    distance = 8.4000000000000004
  }
  [2] = {
    distance = 4.5
  }
}
leastDistancePlace: Place? = (distance = 1.5) {
  distance = 1.5
}
 11>  

答案 1 :(得分:1)

let sortedPlaces = places.sorted(by: { $0.distance < $1.distance })
let first = sortedPlace.first

只需使用sort

答案 2 :(得分:1)

你的问题措辞不多,但我想我知道你要问的是什么。映射函数通常用于转换:

let distances = places.map({ (place: Place) -> Int in
    place.distance
})

简写

let distances = places.map({ $0.distance }) 

然后,您可以对此整数数组使用max或min,以便提取所需的值。