如何使用2D数组填充表格视图?

时间:2019-04-19 20:35:39

标签: swift uitableview multidimensional-array

我有2个数组:roomsArray:[Auditorie]groupsArray:[Group]。我将它们附加到roomsAndGroups:[[Any]]中。问题是如何用2D数组或2个不同类型的数组填充tableView。

struct Auditorie: Codable {
    let id: Int
    let name: String
    let building: Building
}

struct Building: Codable {
    let name: String
    let abbr: String
}

struct Group: Codable {
    let id: Int
    let name: String
}

fileprivate var roomsArray:[Auditorie] = []
fileprivate var groupsArray:[Group] = []
fileprivate var roomsAndGroups:[[Any]] = []


数组看起来像这样

[[PolyStudents.Group(id: 26025, name: "23254/1"), PolyStudents.Group(id: 26605, name: "43325/2"), PolyStudents.Group(id: 26615, name: "43325/3"), PolyStudents.Group(id: 27121, name: "53325/3"), PolyStudents.Group(id: 26055, name: "33254/1"), PolyStudents.Group(id: 26056, name: "33253/1"), PolyStudents.Group(id: 25976, name: "13254/1"), PolyStudents.Group(id: 26026, name: "23255/1"), PolyStudents.Group(id: 26604, name: "43325/1"), PolyStudents.Group(id: 26057, name: "33255/1")], [PolyStudents.Auditorie(id: 1579, name: "1325", building: PolyStudents.Building(name: "50 учебный корпус", abbr: "50 уч.к")), PolyStudents.Auditorie(id: 1641, name: "325", building: PolyStudents.Building(name: "11-й учебный корпус", abbr: "11 к."))]]

1 个答案:

答案 0 :(得分:1)

我可以看到两种方法来实现这一目标。首先,按照ielyamani的评论,您可以使用通用协议。其次,可以将类型包装在枚举中。

选项1

假设name属性是您的类型中唯一的常见属性。因此,您可以创建如下协议:

protocol Nameable {
  var name: String { get }
}

然后使您的类型符合以下要求:

struct Auditorie: Codable, Nameable {
  let id: Int
  let name: String
  let building: Building
}

struct Building: Codable, Nameable {
  let name: String
  let abbr: String
}

struct Group: Codable, Nameable {
  let id: Int
  let name: String
}

因此,您的roomsAndGroups现在应由Nameable组成:

var roomsAndGroups: [[Nameable]]()

在表视图的数据源方法中,您可以获取这些可命名对象并填充表:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  var nameable = roomsAndGroups[indexPath.section][indexPath.row]

  ...

  cell.textLabel?.text = nameable.name
  return cell
}

选项2

使用以下枚举将类型包装起来:

enum Wrapper {
  case auditorie(Auditorie)
  case group(Group)
}

您的roomsAndGroups和表视图数据源方法的相应更改:

var roomsAndGroups: [[Wrapper]]()

...

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  var wrapper = roomsAndGroups[indexPath.section][indexPath.row]
  switch wrapper {
  case .auditorie(let auditorie):
    // Handle cell dequeuing with auditorie object
  case .group(let group):
    // Handle cell dequeuing with group object
  }
}