【问题标题】:How to find object with smallest property value in a Swift object array?如何在 Swift 对象数组中找到具有最小属性值的对象?
【发布时间】:2017-03-24 18:21:20
【问题描述】:

我有以下 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)]

我需要获得距离最短的地方。 我尝试使用

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

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

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

PS:

根据@robmayoff 的回答,我在操场上尝试了以下操作,但一直出现错误:

类型 [Place] 的值无成员 min

请查看此屏幕截图。

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

【问题讨论】:

  • 您应该使用maxmin(如引用的答案),而不是map
  • “它不起作用”信息不足。它是如何失败的?你得到一个编译时错误吗?您是否收到运行时错误?它是否编译并运行但产生错误的答案?请编辑您的问题以包含这些详细信息。
  • 顺便说一句,在您的尝试中,您说的是places.map,但您链接的答案是places.max。也许你想说places.min
  • 为什么你leave a comment在引用的答案“它应该是地图”然后问一个新的问题“地图不起作用”?
  • 我已将您更新的代码复制到一个新的 Xcode 8.2.1/Swift 3 项目中,它可以毫无问题地编译(和运行)。

标签: arrays swift min


【解决方案1】:
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>  

【讨论】:

  • 请检查更新后的问题。它很奇怪。我相信您的解决方案应该有效,但它没有。
  • @toing_toing,在 Swift 2.2 中使用 minElement 而不是 min。你真的应该更新到 Swift 3 和最新的 Xcode。
【解决方案2】:
let sortedPlaces = places.sorted(by: { $0.distance < $1.distance })
let first = sortedPlace.first

只使用排序

【讨论】:

  • 如果您需要最小(或最大)的元素,那么 max/min 比对数组排序更有效。
  • min(by:)。 O(n) 而不是 O(nlog(n))。
  • 哦,我的错,忘了min =)
【解决方案3】:

您的问题措辞不佳,但我想我知道您要问什么。映射函数一般用于变换:

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

速记

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

然后你可以在这个整数数组上使用 max 或 min 来提取你想要的值。

【讨论】:

    猜你喜欢
    • 2014-05-07
    • 2018-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-14
    • 1970-01-01
    • 2019-05-02
    • 2013-10-14
    相关资源
    最近更新 更多