Home > Mobile >  How can I find the min value of an array in a custom condition in Swift?
How can I find the min value of an array in a custom condition in Swift?

Time:08-12

I have to custom types, which I am building an array of it, like this:

struct MyType {
    var id: String
    var value: Double
}

struct CustomObjectType {
    var size: CGFloat
    var myType: MyType
}

Here is my array:

let collection: Array<CustomObjectType> = [CustomObjectType(size: 350.0, myType: MyType(id: "A", value: 0)),
                                       CustomObjectType(size: 200.0, myType: MyType(id: "B", value: 1)),
                                       CustomObjectType(size: 170.0, myType: MyType(id: "C", value: 2)),
                                       CustomObjectType(size: 200.0, myType: MyType(id: "D", value: 3)),
                                       CustomObjectType(size: 200.0, myType: MyType(id: "E", value: 4))]

Here I am trying to find max and min with my custom condition, but it does not work for finding min value.

let maxElement = collection.max(by: { lhs, rhs in
    
    if (lhs.myType.value < rhs.myType.value) {
        return true
    }
    else {
        return false
    }
    
})

let minElement = collection.min(by: { lhs, rhs in
    
    if (lhs.myType.value > rhs.myType.value) {
        return true
    }
    else {
        return false
    }
    
})


print(maxElement?.myType.id, maxElement?.myType.value)
print(minElement?.myType.id, minElement?.myType.value)

result:

Optional("E") Optional(4.0)

Optional("E") Optional(4.0)

CodePudding user response:

Both max(by:) and min(by:) take a predicate function named areInIncreasingOrder which should return true iff the predicate's first argument is less than the predicate's second argument.

But when your code calls min(by:), it is passing a predicate that returns true if its first argument is greater than its second argument. This makes min(by:) return the maximum instead of the minimum.

So, change this:

    if (lhs.myType.value > rhs.myType.value) {

to this:

    if (lhs.myType.value < rhs.myType.value) {
  • Related