skip to Main Content

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.

2

Answers


  1. Well the complexity of array.max() of Swift is O(N) just like the for-in loop.

    There are two ways to for-in in Swift.

    First solution (for-in here like for each value)

    let arr = [1, 4, 3]
    var max = Int.min
    
    // get each value
    for val in arr {
        if (max < val) {
            max = val
        }
    }
    

    Second solution (for-in here is for each index)

    let arr = [1, 4, 3]
    var max = Int.min
    
    // get each index
    for i in 0..<arr.count {
        if (max < arr[i]) {
            max = arr[i]
        }
    }
    

    Two ways have the same output. Feel free when choosing which to use in your further code.

    Login or Signup to reply.
  2. 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"
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search