我正在尝试在 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/