json - "Value of type [Shelter] has not member ' 名称 '"

标签 json swift performselector

我正在尝试在 Swift 中解析某个 JSON 的端点,并使用 name 成员作为我的单元格的标题。我创建了一个结构,它符合端点提供的数据。但是,当尝试将其用作我的单元格名称时,出现错误 Value of type [Shelter] has not member 'name'

一些代码片段:

这是我定义的结构:

避难所.swift:

struct Shelters: Codable {
    var objects: [Shelter]
}

庇护所.swift:

struct Shelter: Codable {
    var name: String
    var shortdescription: String
    var lastedited: String
}

最后,这是来 self 的 ViewController。

var shelters = [Shelter]()


override func viewDidLoad() {
    super.viewDidLoad()

    performSelector(inBackground: #selector(backgroundProc), with: nil)
}

@objc func backgroundProc() {
    let shelterUrl = "https://192.168.1.10/api/shelters/?format=json"
    if let url = URL(string: shelterUrl) {
        if let data = try? Data(contentsOf: url) {
            parse(json: data)
        }
    }
}

//JSON Parser
func parse(json: Data) {

    let decoder = JSONDecoder()

    if let jsonShelters = try? decoder.decode(Shelters.self, from: json) {
        shelters = jsonShelters.objects
    }
}

这是代码失败的地方:

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
   return shelters.count
}


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Shelters", for: indexPath)
    cell.textLabel?.text = shelters.name[indexPath.row] //It fails right here. With the error: Value of type '[Shelter]' has no member 'name'
    cell.detailTextLabel?.text = "Shelter"
    return cell
}

最佳答案

使用 cell.textLabel?.text = shelters[indexPath.row].name

关于json - "Value of type [Shelter] has not member ' 名称 '",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56830690/

相关文章:

json - 如何解析 JSON 输入

ios - 如何使用 Realm 保存图像数组

ios - Swift 5 - Facebook 登录 : LoginManager() always return cancelled

ios - Coregraphics (iOS) 中的内存管理

iphone - iOS - 延迟后的 Web 服务请求

php - 如何在 PHP 中正确 json_encode ["number"=> 12, "color"=> "1e3673"]?

java - 需要表格格式的 Json 结果

javascript - 如何为 Object.define() 定义的属性创建唯一的 toJSON 方法

swift - 错误 : Cannot subscript a value of 'Dictionary with an index of type ' Int64'