user3653575
user3653575

Reputation: 39

How do you sort NSMutableArray from JSON in swift?

I made a UITableview with NSMutableArray, having data downloaded from server in form of JSON. When I perform the table cell the code goes like below.

if let rstrntName = self.items[indexPath.row]["rstrnt_name"] as? NSString {
    cell.rstrntName.text = rstrntName
}

Now I want to sort it by a column named "rstrnt_name". Below is the code I tried, but it doesn't work.

self.items.sortedArrayUsingComparator({obj1, obj2 -> NSComparisonResult in
    let rstrnt1: NSDictionary = obj1 as NSDictionary
    let rstrnt2: NSDictionary = obj2 as NSDictionary
    if (rstrnt1["rstrnt_name"] as String) < (rstrnt2["rstrnt_name"] as String) {
        return NSComparisonResult.OrderedAscending
    }
    if (rstrnt1["rstrnt_name"] as String) > (rstrnt2["rstrnt_name"] as String) {
        return NSComparisonResult.OrderedDescending
    }
    return NSComparisonResult.OrderedSame
})

How can I sort objects in such type?

Upvotes: 0

Views: 1456

Answers (3)

zinnuree
zinnuree

Reputation: 1131

Assign the sorted array to anywhere and check -

self.items = self.items.sortedArrayUsingComparator(//rest of your code

should give you the sorted result.

Upvotes: 1

mustafa
mustafa

Reputation: 15464

Here is swift Array types sort method with pattern matching. This sort method directly mutates items doesn't return new one.

var items: [[String: AnyObject]] = [["rstrnt_name": "mustafa"], ["rstrnt_name": "Ray"], ["rstrnt_name": "Ali"]]

items.sort { (left, right) -> Bool in
    let first = left["rstrnt_name"] as? String
    let second = right["rstrnt_name"] as? String

    switch (first, second) {
    case let (.Some(x), .Some(y)): return x < y
    default: return false
    }
}

Upvotes: 1

Ian MacDonald
Ian MacDonald

Reputation: 14010

self.items.sortedArrayUsingComparator returns a sorted array which you appear to be throwing away to the ether. Try storing the value instead.

Upvotes: 1

Related Questions