'Swift: Using a for-in loop, find the largest value in an Int array

Sorry guys, I'm new here and I'm learning iOS developing from scratch.

I know that in order to find the largest value in an array of Int, we can use the propertie ".max()". But I need to do this using a for-in loop. Would someone please help me? I know it's so easy, but I can't find it and can't find out how to do it on my own as well. Thanks.



Solution 1:[1]

If your array is empty, then returning Int.min as the maximum value is not correct.

Returning an optional is more correct:

var max: Int? = nil

for val in arr {
    guard let maxSoFar = max else {
        max = val
        continue
    }

    if val > maxSoFar {
        max = val
    }
}

Though you might prefer to write it as an extension to Collection, like:

extension Collection where Element: Comparable {
    func mMax() -> Element? {
        var max: Element? = nil

        // get each value
        for val in self {
            guard let maxSoFar = max else {
                max = val
                continue
            }

            if val > maxSoFar {
                max = val
            }
        }

        return max
    }

}

[1, 2, 3].mMax() // 3

([] as [Int]).mMax() // nil

["a", "c", "b"].mMax() // "c"

Or perhaps more generally, so it's not tied to the '>' function, like:

extension Collection {
    func mMax(by compare: (Element, Element) -> Bool) -> Element? {
        var max: Element? = nil

        // get each value
        for val in self {
            guard let maxSoFar = max else {
                max = val
                continue
            }

            if compare(val, maxSoFar) {
                max = val
            }
        }

        return max
    }

}

[1, 2, 3].mMax(by: >) // 3

([] as [Int]).mMax(by: >) // nil


let longestString = ["aaa", "a", "aaaaa"].mMax(by: { $0.count > $1.count })  /// "aaaaa"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Shadowrun