ios - How to display array of a class in tableView cell -


i have class declared variables declared in it.
separate swift file.

class xyz {   var a: string?   var b: string? } 

in other viewcontroller, declaring array of class.

 var arr = [xyz]()  var arr2 = ["title1","title2"] 

after json parsing, appending values in array.

var temp = xyz() var dict = item as! nsdictionary temp.a = (dict.value(forkey: "a") as? string) ?? "" temp.b = (dict.value(forkey: "b") as? string) ?? "" self.arr.append(temp) 

my problem how can display array in cell?

cell.textlabel?.text = arr2[indexpath.row] //the above array shows title of row cell.detailtextlabel?.text = string(describing: arr[indexpath.row]) //indexpath doesn't work here (error: indexpath out of range) //the reason 'arr' array has class in 

the above statement gives error array has class in , not values.

 cell.detailtextlabel?.text = string(describing: arr[0].a)  cell.detailtextlabel?.text = string(describing: arr[0].b) 

is way can access values. due unable display array in tableview.

there many mistakes / bad programming habits in code.

first of name class starting capital letter , declare properties non-optional because going contain non-optional values. (declaring optionals alibi not write initializer 1 of bad habits.)

include title of row arr2 title property in class, avoids out of range exception.

class xyz {     var : string     var b : string     var title : string      init(a: string, b: string, title: string) {         self.a =         self.b = b         self.title = title     } } 

declare data source array

var arr = [xyz]() // `var arr: [xyz]()` not compile 

populate data source array

let dict = item as! [string:any] // swift dictionary !! let temp = xyz(a: dict["a"] as? string) ?? "", b: dict["b"] as? string) ?? "", title: "title1") self.arr.append(temp) // `self.arr.append(value)` not compile 

in cellforrow xyz instance array , use properties

let item = arr[indexpath.row] cell.textlabel?.text = item.title  cell.detailtextlabel?.text = item.a + " " + item.b 

since properties strings anyway, string(describing initializers (create string string) nonsensical.


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -