Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

>Solution :

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) {
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading