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

前端 未结 27 3362
予麋鹿
予麋鹿 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:10

    Swift version: 5.1

    If you have a custom struct or class and want to sort them arbitrarily, you should call sort() using a trailing closure that sorts on a field you specify. Here's an example using an array of custom structs that sorts on a particular property:

        struct User {
            var firstName: String
        }
    
        var users = [
            User(firstName: "Jemima"),
            User(firstName: "Peter"),
            User(firstName: "David"),
            User(firstName: "Kelly"),
            User(firstName: "Isabella")
        ]
    
        users.sort {
            $0.firstName < $1.firstName
        }
    

    If you want to return a sorted array rather than sort it in place, use sorted() like this:

        let sortedUsers = users.sorted {
            $0.firstName < $1.firstName
        }
    

提交回复
热议问题