Sorting of an array alphabetically in swift Sorting of an array alphabetically in swift swift swift

Sorting of an array alphabetically in swift


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 }


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: <)


Swift4

var names = [ "Alpha", "alpha", "bravo", "beta"]var sortedNames = names.sorted { $0.localizedCaseInsensitiveCompare($1) == ComparisonResult.orderedAscending }print(sortedNames) //Logs ["Alpha", "alpha","beta", "bravo"]