"Value of type [Shelter] has not member 'name'"

"Value of type [Shelter] has not member 'name'"

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

一些代码片段:

这是我定义的结构:

Shelters.swift:

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

Shelter.swift:

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

最后,这是我的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

Value of type [Shelter] has not member 'name'

如果您仔细查看错误描述,它会告诉您 Type 的变量:[Shelter] 没有名为 name 的属性。换句话说,<#Obj#>.nameShelter 的 属性 而不是 [Shelter].

所以你需要在失败的行上引用一个对象而不是数组,使用:shelters[indexPath.row],然后你可以访问shelters[indexPath.row].name.

你的行应该是:

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