Reputation: 17333
I have a fullName
property in my Core Data entity Friends
, which has values like:
I want to be able to extract the last name, and sort using these alphabetically, in Swift.
I currently only know how to sort using the full name, like so:
let sortDescriptor = NSSortDescriptor(key: "fullName", ascending: true)
request.sortDescriptors = [sortDescriptor]
Thanks.
Upvotes: 0
Views: 189
Reputation: 13557
You can do as Follow.
1) Fetch all record from core data. (Suppose You have get aryFullname
)
2) Using for loop you can get array only last name as follow.
//Define new mutable array aryfinalData
for i in 0..<aryFullname.count
{
var fullName = aryFullname.ObjectAtindex(i)
var fullNameArr = split(fullName) {$0 == " "}
var lastName: String? = fullNameArr.count > 1 ? fullNameArr[1] : nil
aryfinalData.addObject(lastName)
}
3) Sort Array as follow.
// convert NSMutableArray to the Array by using below line of code.
let arySort = aryfinalData as AnyObject as! [String]
var sortedArray = arySort.sort { $0.name < $1.name }
// sortedArray is your Final array
Note: This is not a efficient solution but you don't have any solution and I am not sure about the above syntax so take care for the same and do changes if any require.
Upvotes: 0