I am trying to parse an endpoint for some JSON in Swift and use the name member as a title of my cell. I have created a struct, which conforms to the data offered by the endpoint. However, when trying to use it as my cell name, I get the error Value of type [Shelter] has not member 'name'.
Some code snippets:
This is my defined structs:
Shelters.swift:
struct Shelters: Codable {
var objects: [Shelter]
}
Shelter.swift:
struct Shelter: Codable {
var name: String
var shortdescription: String
var lastedited: String
}
Finally, this is from my 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
}
}
This is where the code fails:
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
}
Value of type [Shelter] has not member 'name'If you look closely on the error description, it's telling you that a variable of
Type:[Shelter]does not have an attribute namedname. In other words,<#Obj#>.nameis a property ofShelterand NOT[Shelter].So you need to reference an object instead of an array on the failing line, using:
shelters[indexPath.row], and then you can accessshelters[indexPath.row].name.Your line should be:
cell.textLabel?.text = shelters[indexPath.row].name