[SOLVED] Order an array of objects by the value of their enums in swift

Issue

I have an array of CLBeacon objects which all have a property .proximity.

I want to order the array by this property which contains the CLProximity enum. So I want all objects to be in order IMMEDIATE, NEAR, FAR, UNKNOWN.

Is there a way to do this neatly without resorting to a bunch of if statements?

Solution

If you define a (computed read-only) property sortIndex of CLProximity

extension CLProximity {
    var sortIndex : Int {
        switch self {
        case .Immediate:
            return 0
        case .Near:
            return 1
        case .Far:
            return 2
        case .Unknown:
            return 3
        }
    }
}

then you can sort an array of beacons with

let sortedBeacons = sorted(beacons) { $0.proximity.sortIndex < $1.proximity.sortIndex }

If .Unknown is the only CLProximity value that needs
“special treatment” and all other possible values are in the desired
relative order then you can simplify the property definition to

extension CLProximity {
    var sortIndex : Int {
        return self == .Unknown ? Int.max : rawValue
    }
}

Answered By – Martin R

Answer Checked By – Willingham (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.