swiftenumerateswift-extensions

How to get min value from Integer Enum


I have a enum that has an integer representation, and I am going to be iterating over this type in a for loop. I was loop to get both the min and max int value from the enum

    private enum PreloadedArrayDataIndex: Int, CaseIterable {
        case Previous = 0
        case Current = 1
        case Future = 2
    }

in this case, the min should return 0, for .Previous, and would return 2 for .Future.

I was looking to see if there is an easy 'swift' way to do this, something like

let minValue = PreloadedArrayDataIndex.allCases.min
let maxValue = PreloadedArrayDataIndex.allCases.max

I know that I could iterate over all the cases, and check each value against a stored max, but was looking to see if there was a different way I was not aware of.


Solution

  • The integers 0, 1, 2 are the “raw values” of the enumeration, and you can get the smallest and largest of the raw values with

    let minValue = PreloadedArrayDataIndex.allCases.map(\.rawValue).min()! // 0
    let maxValue = PreloadedArrayDataIndex.allCases.map(\.rawValue).max()! // 2
    

    Another option is to make the enumeration comparable, so that you can determine the smallest and largest case:

    enum PreloadedArrayDataIndex: Int, Comparable, CaseIterable {
        
        case previous = 0
        case current = 1
        case future = 2
    
        static func < (lhs: PreloadedArrayDataIndex, rhs: PreloadedArrayDataIndex) -> Bool {
            lhs.rawValue < rhs.rawValue
        }
    }
    
    let minCase = PreloadedArrayDataIndex.allCases.min()! // previous
    let maxCase = PreloadedArrayDataIndex.allCases.max()! // future