0

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?

2

3 Answers 3

1

Assign the sorted array to anywhere and check -

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

should give you the sorted result.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I changed the type into NSArray then the assigning worked.
1

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

Comments

1

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
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.