从2个不同的数组加载表格视图

6 core-data uitableview ios swift

我有 2 个 coredata 数组。一种有 3 个元素,另一种也有 3 个元素。现在我想在我的表格视图中加载这两个数组。所以我的表格视图中总共有 6 行。

我已经取得了这样的成就......

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    let totalCount = (customerDetails.count) + (customerDetails2.count)
    return totalCount
}
Run Code Online (Sandbox Code Playgroud)

我尝试像这样加载这两个数组的数据cellForRowAt...

    let customers = customerDetails[indexPath.row]   //CRASHES HERE
    for i in 0..<(customerDetails.count) {
        cell.nameLabel.text = customers.fname
        if i == customerDetails.count {
            break
        }
    }
    let customers2 = customerDetails2[indexPath.row] 
    for i in 0..<(customerDetails2.count) {
        cell.nameLabel.text = customers2.fname
        if i == customerDetails2.count {
            break
        }
    }
Run Code Online (Sandbox Code Playgroud)

但它在提到的那一行崩溃了,Index out of range可能是因为customerDetails只有 3 行,而加载的单元格总数为 6。

在这种情况下可以做什么?

Nit*_*ish 4

if indexPath.row < customerDetails.count
{
    // load from customerDetails array
    let customer = customerDetails[indexPath.row]
}
else
{
   // load from customerDetails2 array
   let customer = customerDetails2[indexPath.row - customerDetails.count]
}
Run Code Online (Sandbox Code Playgroud)