toing_toing
toing_toing

Reputation: 2442

How to find object with smallest property value in a Swift object array?

I have the following Object Array for the Place class:

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


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

I need to get the Place with the minimum distance. I tried using

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

as per this answer for a similar question, but it gave the following error.

Contextual closure type '(Place) -> _' expects 1 argument, but 2 were used in closure body

PS:

As per @robmayoff 's answer, I tried the following in a playground, but I keep getting an error:

value of Type [Place] no member min

Please check this screenshot. enter image description here

My swift version is : Apple Swift version 2.2 (swiftlang-703.0.18.8 clang-703.0.31)

Upvotes: 4

Views: 5572

Answers (3)

rob mayoff
rob mayoff

Reputation: 385860

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

or

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

Example:

:; 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>  

Upvotes: 18

jnewkirk
jnewkirk

Reputation: 391

Your question is poorly worded however I think I know what you are trying to ask. The mapping function is generally used for tranformations:

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

For shorthand

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

You can then use max or min on this array of integers in order to extract the value you desire.

Upvotes: 1

Daivest
Daivest

Reputation: 66

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

just use sort

Upvotes: 1

Related Questions