Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 881 Vote(s) - 3.45 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How do I sort an NSMutableArray with custom objects in it?

#21
## 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<User>`
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through