Search code examples
arraysxcodeswift3uipickerview

How can I sort this Array in Swift 3 ? ( Picker View ) ( Core Data )


enter image description here

enter image description here

How can I sort this Array in my PickerView ? I am using Swift 3.


Solution

  • Instead of sorting array every time in titleForRow you need to sort it once after you initialized your stores array.

    stores.sort { $0.name < $1.name }
    

    Now stores array is sorted by name property now simply return the name from titleForRow method.

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return stores.count
    }
    
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return stores[row].name
    }
    
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        print(stores[row].name)
    }