4

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

var maxNumber = 0

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

However, I can't use...

let maxStruct = array.maxElement()

because MyStruct 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 n.

1 Answer 1

6

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:

// Swift 2:
let maxStruct = array.maxElement { $0.number < $1.number }
// Swift 3:
let maxStruct = array.max { $0.number < $1.number }
Sign up to request clarification or add additional context in comments.

1 Comment

Ah! Awesome, I didn't know I could use maxElement() that way. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.