Alphabetic array to use in picker

I have an array that i am using in a picker. I would like this array to be alphabetic.


The array is


var item = ["Dog", "Cat", "Ant", "Zoo"]
@State private var selectedItem = 0

The picker is

Picker(selection: $item, label: Text("Item")){
                        ForEach(0 ..< selectedItem.count){
                            //this is the made selection
                            Text(self.item[$0])
                        }
                    }

How would i go about making this alpha, i have tried sort() which didnt work for me. It is however, very possible, that i didnt do it right.


Help is always appreciated.


Kind Regards


Adam

Answered by Claude31 in 423627022

If you replace your declaration by


    var item = ["Dog", "Cat", "Ant", "Zoo"].sorted()


That should work.

Accepted Answer

If you replace your declaration by


    var item = ["Dog", "Cat", "Ant", "Zoo"].sorted()


That should work.

If item array is modified later, you could use a computed var to always use the sirted array:

var sortedItems : [String] = {
     item.sorted()
}
Alphabetic array to use in picker
 
 
Q