Sorting array by alphabetical order not working (swift3)

My code adds a entry to the array but I don’t know how to sort in a alphabetical order. I just want to be able to sort whatever is in yourArray in alphabetical order.

    import UIKit
var yourArray = [String]()

class ViewController: UIViewController {

    @IBOutlet var textA: UITextField!

    @IBAction func store(_ sender: Any) {
        yourArray.append((textA.text!))

        yourArray.sort()
        print(yourArray)

                  }
}

@timswift Thanks very much for your question! If you have an array of Strings, the way to sort them would be to:

var sortedArray:[String] = yourArray.sorted { $0.localizedCaseInsensitiveCompare($1) == ComparisonResult.orderedAscending }

for name in sortedArray {
print(name)
}

This should solve your problem :slight_smile:

All the best!

Thats it thank you so much!

No problem! Anytime :slight_smile:

All the best!

This topic was automatically closed after 166 days. New replies are no longer allowed.