Swift tableView cellForRowAt获取数组的subKeyName的数组

时间:2019-07-23 03:37:01

标签: swift

我有这样的数组数据

var countryData = [Country(code: "01", name: "US", currency: "USD", information: [Information(first: "100", second: "200", third: "300"), information(first: "400", second: "500", third: "600"), information(first: "700", second: "800", third: "900")])]

我需要使用tableView来显示这些数据

在cellForRowAt中,我可以获取国家/地区的值

喜欢

cell.countryNameLabel.text = countryData[indexPath.row].name

但是如果有subKay并且它是​​数组

我应该如何获取该阵列的数据并显示全部?

cell.countryInformationLabel.text = ?

我的手机看起来像

US : 100 200 300, 400 500 600,700 800 900

2 个答案:

答案 0 :(得分:0)

你可以

let information = countryData[indexPath.row].information
cell.countryInformationLabel.text = information
  .map { String(describing: $0) }
  .joined(separator: ", ")

extension Information: CustomStringConvertible {
  var decription: String {
    return "\(first) \(second) \(third)"
  } 
}

如果您认为不必遵守CustomStringConvertible,只需执行以下操作:

let information = countryData[indexPath.row].information
cell.countryInformationLabel.text = information
  .map { "\($0.first) \($0.second) \($0.third)" }
  .joined(separator: ", ")

结果如下:

struct Information {
  var first: String
  var second: String
  var third: String
}

let information = [Information(first: "100", second: "200", third: "300"),
                   Information(first: "300", second: "400", third: "500"),
                   Information(first: "400", second: "500", third: "600")]
print(
  information
    .map { "\($0.first) \($0.second) \($0.third)" }
    .joined(separator: ", ")
)
// 100 200 300, 300 400 500, 400 500 600

答案 1 :(得分:0)

在模型对象中,信息是一个数组。因此,您必须对信息进行循环。请尝试以下代码,这对我来说很好。

cell.countryNameLabel.text = countryData[indexPath.row].name
let informationArr = countryData[indexPath.row].information // This should be an array.
var countryInfoText = ""
for info in informationArr{
    countryInfoText += "\(info.first) \(info.second) \(info.third),"
}
cell.countryInformationLabel.text = countryInfoText