Pete Pete - 1 month ago 4
Swift Question

Sort Through Array Excluding Nil

I am attempting to sort an array which includes variables which are nil.

class TestArray {
var a: String? = nil
var b: String? = nil
init(a: String?, b: String?) {
self.a = a
self.b = b
}
}

let first = TestArray(a: "xxx", b: "yyy")
let second = TestArray(a: "zzz", b: "zzz")
let third = TestArray(a: "aaa", b: nil)

var array = [first, second, third]
array.sort(by: {($0.a as String!) > ($1.a as String!)})

array.sort(by: {($0.b as String!) > ($1.b as String!)}) // Throws an error


How can I sort by
b
and leave the third TestArray with b = nil at the end of the array?
Also I would like to sort through all b and then for the arrays in which b = nil sort the remaining by a.

Answer

I believe this should cover the situations you want without having to iterate more than once (which is expensive)

array.sort { (lessThan, item) -> Bool in

    switch (lessThan.a, lessThan.b, item.a, item.b) {
    // if bs exist, use that comparison
    case (_, .some(let lessThanB), _, .some(let itemB)):
        return lessThanB < itemB
    // if bs don't exist by as do, use that comparison
    case (.some(let lessThanA), .none, .some(let itemA), .none):
        return lessThanA < itemA
    // if one item has a value but the other doesn't, the item with the value should be first
    case (_, .some(_), _, .none), (.some(_), _, .none, _ ):
        return true

    default:
        return false
    }
}