How we can sort(ascending and descending) a uitableview data in swift language
Well, just like it sounds - you'd filter the list:
func filterList() { // should probably be called sort and not filter
fruitArr.sorted() { $0.fruitName > $1.fruitName } // sort the fruit by name
fruitList.reloadData(); // notify the table view the data has changed
}
If you just want to reverse the items rather than actually sort them (to toggle the order) you can perform a fruitArr.reverse()
instead of sorting.
Swift 3+
you can use .sorted()
and .lowercased()
(with string properties) to sort a-z, by default .sorted and .sort sort by A-z.
//Prints Names A-z (0-9 then A-Z then a-z)
fruitArr.sorted() { $0.fruitName > $1.fruitName }
//prints '000', 'Watermelon', 'apple'
//Prints Name in alphabetical order.
fruitArr.sorted() { $0.fruitName.lowercased() > $1.fruitName.lowercased() }
//prints '000', 'apple', 'Watermelon'
See documentation for .sorted()