Getting element with maximum property from array

If I have a structure ...

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 most number...

var maxNumber = 0

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

However, I can not use ...

let maxStruct = array.maxElement()

because it is MyStructnot comparable. I could make it comparable, but then I might also have a date stamp that I want to compare, so making Comparable is not perfect.

Is there any other way to make this more elegant?

....

I just thought I could do it too ...

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

But it will take more time. I'm not sure which sorting method he uses, but it will be n log(n), whereas my original method will be simple n.

+4
1

sort()/sortInPlace(), min/maxElement(): , :

extension SequenceType where Generator.Element : Comparable {

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

:

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?
}

maxElement() :

// Swift 2:
let maxStruct = array.maxElement { $0.number < $1.number }
// Swift 3:
let maxStruct = array.max { $0.number < $1.number }
+6

Source: https://habr.com/ru/post/1622754/


All Articles