【问题标题】:Section Index Titles after Parsing JSON Swift解析 JSON Swift 后的部分索引标题
【发布时间】:2021-03-23 04:32:15
【问题描述】:

我正在尝试为我的 tableView 创建动态 sectionIndexTitles。我想获取所有角色名称,然后获取名称的第一个字母来创建 sectionIndexTitles,但这样做有困难。

我从 URL 获取 JSON:

func downloadJSON(completed: @escaping () -> ()) {
    let url = URL(string: "mytestURL")
    let configuration = URLSessionConfiguration.ephemeral
    let session = URLSession(configuration: configuration)
    
    session.dataTask(with: url!) { (data, response, error) in
        if error == nil {
            do {
                characters = try JSONDecoder().decode([CharacterStats].self, from: data!)
                DispatchQueue.main.async {
                    completed()
                }
            } catch {
                print("JSON Error")
            }
        }
        }.resume()
}

JSON 看起来像这样:

[
 {
  "name": "Batman",
  "type": "DC",
  "gender": "male",
},
{
  "name": "Captain America",
  "type": "Marvel",
  "gender": "male",
},
{
  "name": "Captain Marvel",
  "type": "Marvel",
  "gender": "female",
}
]

我的结构看起来像这样:

public struct CharacterStats: Decodable {
    let name: String
    let type: String?
    let gender: String?
}

【问题讨论】:

  • 您遇到什么错误?可以试试“public struct CharacterStats: Codable”吗?
  • @achu 本身没有错误。我不确定如何仅获取能够提取 indexTitles 的第一个字母的名称。

标签: ios json swift uitableview


【解决方案1】:

我在这里发布了一个示例代码https://github.com/achuaswani/ListItemExample.git

【讨论】:

    猜你喜欢
    • 2018-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-02
    • 1970-01-01
    • 2015-06-09
    • 1970-01-01
    相关资源
    最近更新 更多