Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting of an array alphabetically in swift

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.

like image 979
anusha hrithi Avatar asked Apr 04 '16 04:04

anusha hrithi


People also ask

How do I sort an array alphabetically in Swift?

You can use either sort() or sorted() to sort strings in ascending order.

How do I sort an array in Swift?

To sort the array we use the sort() function. This function is used to sort the elements of the array in a specified order either in ascending order or in descending order. It uses the “>” operator to sort the array in descending order and the “<” operator to sort the array in ascending order.

How do I arrange an array in ascending order in Swift?

To sort an integer array in increasing order in Swift, call sort() method on this array. sort() method sorts this array in place, and by default, in ascending order.


4 Answers

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 }
like image 83
Payal Maniyar Avatar answered Oct 13 '22 12:10

Payal Maniyar


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: <)
like image 21
Moin Shirazi Avatar answered Oct 13 '22 13:10

Moin Shirazi


Swift4

var names = [ "Alpha", "alpha", "bravo", "beta"]
var sortedNames = names.sorted { $0.localizedCaseInsensitiveCompare($1) == ComparisonResult.orderedAscending }
print(sortedNames) //Logs ["Alpha", "alpha","beta", "bravo"]
like image 17
kolisko Avatar answered Oct 13 '22 12:10

kolisko


Swift 4(working code)

JSON response -> Stored in aryNameList

"DATA": [
{
        email = "[email protected]";
        firstname = Harvey
},
{
        email = "[email protected]";
        firstname = poonam
},
{
        email = "[email protected]";
        firstname = rahul
},
{
        email = "[email protected]";
        firstname = Chulbulx
},
{
        email = "[email protected]";
        firstname = rahul
},
{
        email = "[email protected]";
        firstname = Jay
},
{
        email = "[email protected]";
        firstname = Roy
},
{
        email = "[email protected]";
        firstname = Regan
},
{
        email = "[email protected]";
        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..)

like image 13
Krunal Patel Avatar answered Oct 13 '22 12:10

Krunal Patel