1

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?

Aker Abos
  • 21
  • 4

1 Answers1

2

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 }
Alexander
  • 59,041
  • 12
  • 98
  • 151
  • Where should I add that protocol and I suspect that I need to remove the rank property from Person and SportsMan and use Person: Rankable and use the rank inside that property instead or? – Aker Abos Jun 05 '17 at 17:52
  • The existing `rank` property of `Person` and `SportsMan` can fulfill the protocol's requirement. You just need to declare the conformance to `Rankable` for both `Person` and `SportsMan` – Alexander Jun 05 '17 at 17:58