in swift UIKit
I am trying to arrange the data in Table View according to the string variable from API
But it gives me an error
var arrTable = [ModelApiData]()
override func viewDidLoad() {
super.viewDidLoad()
for i in arrTable {
arrTable.sorted(by: i.url)
}
arrTable.sorted(by: ModelApiData)
}
name (url) I want to arrange the cells on it
{
"id": 130,
"user_id": 1,
"title": "test Sort 2",
"details": "ESFFESFSD",
"image_path": null,
"youtube_link": null,
"font_size": 19,
"algiment": "right",
"color": "0 0 0 1",
"url": "2",
"category_id": 2
},
error is
Cannot convert value of type 'String?' to expected argument type '(ModelApiData, ModelApiData) throws -> Bool'
Also, if I use this method, I cannot determine from API
arrTable.sorted(by: ModelApiData)
CodePudding user response:
Your code makes not sense for several reasons:
- The error tells you that you cannot sort just by passing the type. You have to specify one or multiple properties and apply the
<
operator. sorted
returns the sorted array, it does not sort in place.- Sorting in a loop is pointless.
To sort the array by the url
property you have to write
override func viewDidLoad() {
super.viewDidLoad()
arrTable.sort(by: {$0.url < $1.url})
}
Side note: Avoid optionals as much as possible.
CodePudding user response:
arrTable.sorted(by: {$0.url > $1.url})
chose your own ascending or descending sorting way
arrTable.sorted(by: {$0.url > $1.url})
i ll suggest u to make func of sorting
func sortingData(array:[ModelApiData]) -> [ModelApiData] {
return array.sorted(by: {$0.url > $1.url})
}
then use it to number of item in section and
sortingData(array:arrTable).count
and in cell for row at
let data = sortingData(array:arrTable)[indexPath].row
cell.textLabel.text = data.title