46

I am new to swift.I am trying one sample app in which I need to implement the sorting of an array in alphabetical order.I getting the json data and I am adding the titles in the array.Now i would like to sort that alphabetically.Here is my code .....

func updateSearchResults(data: NSData?)
{
    do
    {
            let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)

            if let blogs: NSArray = json["results"] as? [AnyObject] {
                print(blogs)
                for blog in blogs {
                    if let name = blog["original_title"] as? String {
                        names.addObject(name)
                    }
                }
                print(names)
                **let sortedArray = sorted(names, {
                (str1: String, str2: String) -> Bool in
                return str1.toInt() < str2.toInt()** // Here I am getting the Error Message
                })

            }
    }
    catch {
        print("error serializing JSON: \(error)")
    }
}

The error message I am getting is "Cannot invoke 'sorted' with an argument list of type '(NSMutableArray, (String, String) -> Bool)'"

I tried a lot to achieve this but I didn't find the solution. Can anyone help me to resolve this issue. Thanks In Advance.

INDIA IT TECH
  • 1,902
  • 4
  • 12
  • 25
anusha hrithi
  • 709
  • 2
  • 9
  • 13

7 Answers7

93

First convert NSMutableArray to the Array by using below line of code.

let swiftArray = mutableArray as AnyObject as! [String]

Use below line of code to sort the Array.

var sortedArray = names.sorted { $0.localizedCaseInsensitiveCompare($1) == NSComparisonResult.OrderedAscending }

Check below link for sort Closures. https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html

Update for Swift 3.0

var sortedArray = swiftArray.sorted { $0.localizedCaseInsensitiveCompare($1) == ComparisonResult.orderedAscending }
shim
  • 9,289
  • 12
  • 69
  • 108
Payal Maniyar
  • 4,293
  • 3
  • 25
  • 51
  • It is showing the error like "Value of type 'NSMutableArray' has no member 'sorted' – anusha hrithi Apr 04 '16 at 05:02
  • @anushahrithi `sorted` was removed, use `sort` instead. –  Apr 04 '16 at 05:05
  • you must pass an array of sort descriptors (even if it's only one): var descriptor: NSSortDescriptor = NSSortDescriptor(key: "name", ascending: true) var sortedResults: NSArray = results.sortedArrayUsingDescriptors([descriptor]) – Jigar Apr 04 '16 at 05:06
39

Use this simple code of line to sort ur array

 let sortedNames = names.sort { $0.name < $1.name }

For Swift 4 you can use only this

let sortedNames = names.sorted(by: <)
Moin Shirazi
  • 4,372
  • 2
  • 26
  • 38
  • @Kenneth Yes, in this scenario this will also work fine – Moin Shirazi Apr 04 '16 at 07:23
  • 3
    Since `names` looks to have the type `Array` it wouldn't have the property `name`. Your call should look like `names.sort { $0 < $1 }`. That can even be shorted to `names.sort(<)`. –  Apr 04 '16 at 07:28
  • This doesn't take into account capitalization (and likely other things when translating to other languages). For example "Bag" would come before "art". – jjatie Oct 21 '16 at 17:44
  • Also, you can now just write `.sorted()` to sort in ascending order. – jjatie Oct 21 '16 at 17:47
  • Thanks @jjatie ... You can edit the answer and update if you have verified and tested the code – Moin Shirazi Oct 22 '16 at 04:05
17

Swift4

var names = [ "Alpha", "alpha", "bravo", "beta"]
var sortedNames = names.sorted { $0.localizedCaseInsensitiveCompare($1) == ComparisonResult.orderedAscending }
print(sortedNames) //Logs ["Alpha", "alpha","beta", "bravo"]
Manee ios
  • 1,112
  • 11
  • 14
kolisko
  • 1,548
  • 3
  • 17
  • 22
14

Swift 4(working code)

JSON response -> Stored in aryNameList

"DATA": [
{
        email = "iosworker@gmail.com";
        firstname = Harvey
},
{
        email = "poonam@openxcell.com";
        firstname = poonam
},
{
        email = "t@t.com";
        firstname = rahul
},
{
        email = "android.testapps@gmail.com";
        firstname = Chulbulx
},
{
        email = "t@t2.com";
        firstname = rahul
},
{
        email = "jaystevens32@gmail.com";
        firstname = Jay
},
{
        email = "royronald47@gmail.com";
        firstname = Roy
},
{
        email = "regmanjones@hotmail.com";
        firstname = Regan
},
{
        email = "jd@gmail.com";
        firstname = Jaydip
}
]

Code

    self.aryNameList = self.aryNameList.sorted(by: { (Obj1, Obj2) -> Bool in
       let Obj1_Name = Obj1.firstname ?? ""
       let Obj2_Name = Obj2.firstname ?? ""
       return (Obj1_Name.localizedCaseInsensitiveCompare(Obj2_Name) == .orderedAscending)
    })

working every case (for ex: lowerCase, upperCase..)

Mandeep Singh
  • 2,810
  • 1
  • 19
  • 31
Krunal Patel
  • 1,649
  • 1
  • 14
  • 22
9

For an array of objects:

items = items.sorted(by: { (item1, item2) -> Bool in
        return item1.product.name.compare(item2.product.name) == ComparisonResult.orderedAscending
    })
Giggs
  • 851
  • 10
  • 16
0

Try this one

var names = [ "Alpha", "alpha", "bravo"]
var sortedNames = names.sort { $0.localizedCaseInsensitiveCompare($1) == NSComparisonResult.OrderedAscending }
print(sortedNames) //Logs ["Alpha", "alpha", "bravo"]
Droid GEEK
  • 192
  • 2
  • 11
0

Swift 3 solution:

let yourStringArray = [ "beTA", "ALPha", "Beta", "Alpha"]
var sortedArray = yourStringArray.sorted()
// Result will be ["ALPha", "Alpha", "Beta", "beTA"]

Creds to jjatie

Erik Nguyen
  • 346
  • 2
  • 6