orthehelper
orthehelper

Reputation: 4079

Resort Swift Array - Move Object with empty name to the end of array

I have an array that I'm sorting as follows:

contactsArray = unified.sorted{$0.name.localizedCaseInsensitiveCompare($1.name) == ComparisonResult.orderedAscending}

The problem is I want object with empty string ex "" to be moved to the end of the array. Looking for the most efficient solution here.

Upvotes: 1

Views: 167

Answers (1)

nayem
nayem

Reputation: 7605

Try this:

contactsArray = unified.sorted { (a, b) -> Bool in
    if a.name.isEmpty {
        return false
    } else if b.name.isEmpty {
        return true
    } else {
        return a.name.localizedCaseInsensitiveCompare(b.name) == .orderedAscending
    }
}

Upvotes: 2

Related Questions