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

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

    Sort Array In Swift


    For Swifty Person below is a very clean technique to achieve above goal for globally. Lets have an example custom class of User which have some attributes.

    class User: NSObject {
        var id: String?
        var name: String?
        var email: String?
        var createdDate: Date?
    }
    

    Now we have an array which we need to sort on the basis of createdDate either ascending and/or descending. So lets add a function for date comparison.

    class User: NSObject {
        var id: String?
        var name: String?
        var email: String?
        var createdDate: Date?
        func checkForOrder(_ otherUser: User, _ order: ComparisonResult) -> Bool {
            if let myCreatedDate = self.createdDate, let othersCreatedDate = otherUser.createdDate {
                //This line will compare both date with the order that has been passed.
                return myCreatedDate.compare(othersCreatedDate) == order
            }
            return false
        }
    }
    

    Now lets have an extension of Array for User. In simple words lets add some methods only for those Array's which only have User objects in it.

    extension Array where Element: User {
        //This method only takes an order type. i.e ComparisonResult.orderedAscending
        func sortUserByDate(_ order: ComparisonResult) -> [User] {
            let sortedArray = self.sorted { (user1, user2) -> Bool in
                return user1.checkForOrder(user2, order)
            }
            return sortedArray
        }
    }
    

    Usage for Ascending Order

    let sortedArray = someArray.sortUserByDate(.orderedAscending)
    

    Usage for Descending Order

    let sortedArray = someArray.sortUserByDate(.orderedAscending)
    

    Usage for Same Order

    let sortedArray = someArray.sortUserByDate(.orderedSame)
    

    Above method in extension will only be accessible if the Array is of type [User] || Array

提交回复
热议问题