Reordering custom arrays

Is there a better way to do this? I want the order in the array to be: Initials -> Damage -> Option -> Condition -> Unrelated

struct claimData {
    var isAnInitial = Bool()
    var isDamage = Bool()
    var isUnrelated = Bool()
    var isAnOption = Bool()
    var isACondition = Bool()
}

func constructPrintableArray() -> [claimData] {
        var initialsArray = [claimData]()
        var damageArray = [claimData]()
        var unrelatedArray = [claimData]()
        var optionsArray = [claimData]()
        var conditionsArray = [claimData]()
        
        for claimData in reviewDataController.tableViewReviewData {
            if claimData.isAnInitial {
                initialsArray.append(claimData)
            } else if claimData.isDamage {
                damageArray.append(claimData)
            } else if claimData.isUnrelated {
                unrelatedArray.append(claimData)
            } else if claimData.isAnOption {
                optionsArray.append(claimData)
            } else {
                conditionsArray.append(claimData)
            }
        }
        
        var finalArray = [claimData]()
        finalArray.append(contentsOf: initialsArray)
        finalArray.append(contentsOf: damageArray)
        finalArray.append(contentsOf: optionsArray)
        finalArray.append(contentsOf: conditionsArray)
        finalArray.append(contentsOf: unrelatedArray)
        
        return finalArray
    }

You could make claimData (typically you'd want to capitalize the first letter of a type name btw) conform to Comparable, then just sort the array.

1 Like

Though that would make it O(N*logN) vs the current O(N), which aspect might be important.

1 Like

True. log N on something that fits in a UI is probably ignorably small, but always good to be aware of the possibility.

Somewhat shorter (untested):

struct ClaimData {
    enum Kind: Int, CaseIterable {
        case initial
        case damage
        case option
        case condition
        case unrelated
    }
    let kind: Kind
    // other fields go here, I assume
}

func constructPrintableArray() -> [ClaimData] {
    var arrays: [[ClaimData]] = .init(repeating: [], count: ClaimData.Kind.allCases.count)
    
    for claimData in reviewDataController.tableViewReviewData {
        arrays[claimData.kind.rawValue].append(claimData)
    }
    
    return arrays.flatMap { $0 }
}

3 Likes