anto0522
anto0522

Reputation: 672

How can I find the highest Int in a Struct in Swift

Assuming I have a struct such as:

struct TestStruct {
    var name: String
    var rank: Int
}

var foo1 = [TestStruct]()

What is the most efficient way to find the highest rank value inside foo1 ? Is it somehow possible to use maxElement()on a Struct ?

Upvotes: 2

Views: 1210

Answers (2)

Kametrixom
Kametrixom

Reputation: 14983

Or you can make your struct conform to the Comparable protocol:

struct Test : Comparable {
    let rank: Int
}

func ==(lhs: Test, rhs: Test) -> Bool {
    return lhs.rank == rhs.rank
}

func <(lhs: Test, rhs: Test) -> Bool {
    return lhs.rank < rhs.rank
}

let foo1 = [
    Test(rank: 4),
    Test(rank: 8),
    Test(rank: 2),
    Test(rank: 7)
]

Then you can use foo1.maxElement() with Swift 2 or maxElement(foo1) with Swift 1.2

Upvotes: 2

Eric Aya
Eric Aya

Reputation: 70113

Yes you can with Swift 2:

let max = foo1.maxElement({ $0.rank < $1.rank })

Here's an example with data:

struct TestStruct {
    var name = ""
    var rank: Int
    init(rank: Int) {
        self.rank = rank
    }
}

let foo1 = [TestStruct(rank: 2), TestStruct(rank: 5), TestStruct(rank: 12)]

let mx = foo1.maxElement({ $0.rank < $1.rank })

print(mx!) // TestStruct(name: "", rank: 12)

EDIT

With Swift 1.2 you have to overload the operators like with Kametrixom's answer, then you will write

maxElement(foo1)

instead of

foo1.maxElement()

Upvotes: 3

Related Questions