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

toi*_*ing 0 arrays min swift

我有以下用于 Place 类的对象数组:

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


let places = [Place(1.5), Place(8.4), Place(4.5)]
Run Code Online (Sandbox Code Playgroud)

我需要以最小距离到达 Place。我尝试使用

let leastDistancePlace = places.min { $0.distance > $1.distance }
Run Code Online (Sandbox Code Playgroud)

根据this answer for a similar question,但它给出了以下错误。

上下文闭包类型 '(Place) -> _' 需要 1 个参数,但在闭包主体中使用了 2 个

PS:

根据@robmayoff 的回答,我在操场上尝试了以下操作,但我不断收到错误消息:

Type [Place] 的值 no member min

请检查此屏幕截图。 在此处输入图片说明

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

rob*_*off 12

let leastDistancePlace = places.min { $0.distance < $1.distance }
Run Code Online (Sandbox Code Playgroud)

或者

let leastDistancePlace = places.min(by: { $0.distance < $1.distance })
Run Code Online (Sandbox Code Playgroud)

例子:

:; 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>  
Run Code Online (Sandbox Code Playgroud)

  • @toing_toing,在 Swift 2.2 中使用 `minElement` 而不是 `min`。你真的应该更新到 Swift 3 和最新的 Xcode。 (3认同)