简体   繁体   中英

Table updates from JSON array but sorting alphabetically causes error in Swift 3

In my iOS app, I populate a table from an external json file. That works fine now, the problem I am running into is that I need to sort the table alphabetically.

I've added a compare method, and printing it will give me the correct output (a list of results organized by their show_name ). However, when I try to append those results to the table, I get an error.

Here's my code:

func extract_json(_ data: Data)
{
    let json: Any?
    do{
        json = try JSONSerialization.jsonObject(with: data, options: [])
    }
    catch{
        return
    }

    guard let data_list = json as? NSArray else {
        return
    }

    if let shows_list = json as? NSArray
    {
        for i in 0 ..< data_list.count
        {
            if let shows_obj = shows_list[i] as? NSDictionary
            {
                let show_name = shows_obj["show"] as? String
                let show_image = shows_obj["thumbnail"] as? String
                TableData.append(show_name!)
                var sortedArray = TableData.sorted { $0.localizedCaseInsensitiveCompare($1) == ComparisonResult.orderedAscending }
                print(sortedArray)

If I change the TableData.append(show_name!) to TableData.append(sortedArray) , I get the error "Cannot convert value of type '[String]?' to expected argument type 'String'".

Is there a safer/smarter way to alphabetize my json array by an attribute before loading it into the table (than trying to load it into the TableData and then comparing, like I am now)?

I think TableData is the array of String and you are trying to append String Array in it. That is the reason you are getting this error.

You should do like this,

TableData.append(contentsOf: sortedArray) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM