Fogmeister Fogmeister - 4 years ago 323
Swift Question

Getting element with max property from array

If I have a struct...

struct MyStruct {
let number: Int

and I have an array of them...

var array = [MyStruct]()
// populate array with MyStructs

Then I can do this to get the maximum

var maxNumber = 0

for tempStruct in array where tempStruct.number > maxNumber {
maxNumber = tempStruct.number

However, I can't use...

let maxStruct = array.maxElement()

is not comparable. I could make it comparable but then I might also have a date stamp that I want to compare by so making it Comparable isn't ideal.

Is there another way I could do this that is more elegant?


I just thought, I could also do this...

let maxStruct = array.sort{$0.number > $1.number}.first()

But this will take more time. I'm not sure which sort method it uses but it'll prob be
n log(n)
whereas my initial method will just be

Answer Source

As with sort()/sortInPlace(), there are also two variants of min/maxElement(): The first requires that the sequence elements are comparable:

extension SequenceType where Generator.Element : Comparable {

    public func minElement() -> Self.Generator.Element?
    public func maxElement() -> Self.Generator.Element?

The second has no such restriction and takes the comparator as an argument instead:

extension SequenceType {

    public func minElement(@noescape isOrderedBefore: (Self.Generator.Element, Self.Generator.Element) throws -> Bool) rethrows -> Self.Generator.Element?
    public func maxElement(@noescape isOrderedBefore: (Self.Generator.Element, Self.Generator.Element) throws -> Bool) rethrows -> Self.Generator.Element?

In your case, you can use maxElement() with a comparator function:

let maxStruct = array.maxElement { $0.number < $1.number }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download