Reputation: 181
I am using SwiftyJSON to parse the JSON from web, and then displaying those values in a tableView. I want to add a functionality to sort the data alphabetically ascending or descending according to the user names. I am new to Swift and having trouble sorting this. I would appreciate any help!
override func viewDidLoad(){
super.viewDidLoad()
getContactListJSON()
}
func getContactListJSON(){
let urlString = "http://jsonplaceholder.typicode.com/users"
let urlEncodedString = urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
let url = NSURL( string: urlEncodedString!)
var task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, innerError) in
self.json = JSON(data: data)
self.contactsArray = json.arrayValue
dispatch_async(dispatch_get_main_queue(), {
}
task.resume()
}
This is how I am populating my tableView.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as? UITableViewCell
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.Value2, reuseIdentifier: "Cell")
}
cell!.textLabel?.text = self.contactsArray[indexPath.row]["name"].stringValue
cell!.detailTextLabel?.text = self.contactsArray[indexPath.row]["email"].stringValue
return cell!
}
Upvotes: 2
Views: 5211
Reputation: 2587
After playing around a bit I found a more swift-friendly answer. I will leave the Objective-C style below as reference in case it's interesting. Of note – in this first example, the array being sorted must be mutable (var not let) for sort() to work. In the second example with Obj-C sort descriptors a new array is created and the original isn't mutated - similar to sorted()
let contact1: [String: String] = ["name" : "Dare", "email" : "[email protected]"]
let contact2: [String: String] = ["name" : "Jack", "email" : "[email protected]"]
let contact3: [String: String] = ["name" : "Adam", "email" : "[email protected]"]
var contacts = [contact1, contact2, contact3]
contacts.sort({$0["name"] < $1["name"]})
println(contacts)
This is corrupted a bit by Objective-C but seems to work. The major benefit of this method over the other is that this is case-insensitive. Although I am sure there is a better way to do the same thing with newer syntax.
let contact1: [String: String] = ["name" : "Dare", "email" : "[email protected]"]
let contact2: [String: String] = ["name" : "Jack", "email" : "[email protected]"]
let contact3: [String: String] = ["name" : "Adam", "email" : "[email protected]"]
let contacts: Array = [contact1, contact2, contact3]
let nameDiscriptor = NSSortDescriptor(key: "name", ascending: true, selector: Selector("caseInsensitiveCompare:"))
let sorted = (contacts as NSArray).sortedArrayUsingDescriptors([nameDiscriptor])
println(sorted)
//These print the following
[
{
email = "[email protected]";
name = Adam;
},
{
email = "[email protected]";
name = Dare;
},
{
email = "[email protected]";
name = Jack;
}
]
Upvotes: 0