swiftfilteranyobject

Filter array of Any based on variable


I have an array of type Any in that array there are two different types, Person and SportsMan both these has a value called rank. I want to sort my array based on the rank. Here is how I have done it today and it works:

self.persons.sort {
    let a = ($0 as AnyObject) as? Person
    let b = ($0 as AnyObject) as? SportsMan
    let l = a?.rank ?? b?.rank

    let c = ($1 as AnyObject) as? Person
    let d = ($1 as AnyObject) as? SportsMan
    let r = c?.rank ?? d?.rank
    return l! < r!
}

I´m feeling a bit unsure because of the ! in l! < r!. Is this a good way to solve this or is it any built in function to use for this?


Solution

  • Make a protocol such as Rankable, and make Person and SportsMan conform to it.

    protocol Rankable {
        var rank: Int { get }
    }
    

    Then make your array into an [Rankable] (a.k.a. Array<Rankable>) rather than [Any], and sort it like so:

    self.persons.sort{ $0.rank < $1.rank }