How do I sort an NSMutableArray with custom objects in it?

前端 未结 27 3307
予麋鹿
予麋鹿 2020-11-21 04:45

What I want to do seems pretty simple, but I can\'t find any answers on the web. I have an NSMutableArray of objects, and let\'s say they are \'Person\' objects

27条回答
  •  醉酒成梦
    2020-11-21 05:02

    Swift's protocols and functional programming makes that very easy you just have to make your class conform to the Comparable protocol, implement the methods required by the protocol and then use the sorted(by: ) high order function to create a sorted array without need to use mutable arrays by the way.

    class Person: Comparable {
        var birthDate: NSDate?
        let name: String
    
        init(name: String) {
            self.name = name
        }
    
        static func ==(lhs: Person, rhs: Person) -> Bool {
            return lhs.birthDate === rhs.birthDate || lhs.birthDate?.compare(rhs.birthDate as! Date) == .orderedSame
        }
    
        static func <(lhs: Person, rhs: Person) -> Bool {
            return lhs.birthDate?.compare(rhs.birthDate as! Date) == .orderedAscending
        }
    
        static func >(lhs: Person, rhs: Person) -> Bool {
            return lhs.birthDate?.compare(rhs.birthDate as! Date) == .orderedDescending
        }
    
    }
    
    let p1 = Person(name: "Sasha")
    p1.birthDate = NSDate() 
    
    let p2 = Person(name: "James")
    p2.birthDate = NSDate()//he is older by miliseconds
    
    if p1 == p2 {
        print("they are the same") //they are not
    }
    
    let persons = [p1, p2]
    
    //sort the array based on who is older
    let sortedPersons = persons.sorted(by: {$0 > $1})
    
    //print sasha which is p1
    print(persons.first?.name)
    //print James which is the "older"
    print(sortedPersons.first?.name)
    

提交回复
热议问题