如何比较两个不同大小的数组并根据比较在UICollectionviewcell中给出颜色?

时间:2016-12-25 08:31:54

标签: ios arrays uitableview swift3

我必须将下面的数组相互比较。但是我在for循环和cellForItemAtIndexPath中得到索引超出范围错误。如何比较这些数组并在UICollectionviewcell中分配3种不同的颜色。三个阵列有不同的大小?

{
"success": 1,
"time_slots": [
"10:00",
"10:15",
"10:30",
"10:45",
"11:00",
"11:15",
"11:30",
"11:45",
"12:00",
"12:15",
"12:30",
"12:45",
"13:00",
"13:15",
"13:30",
"13:45",
"14:00",
"14:15",
"14:30",
"14:45",
"15:00",
"15:15",
"15:30",
"15:45",
"16:00",
"16:15",
"16:30",
"16:45",
"17:00",
"17:15",
"17:30",
"17:45",
"18:00",
"18:15",
"18:30",
"18:45",
"19:00",
"19:15",
"19:30",
"19:45",
"20:00",
"20:15",
"20:30",
"20:45",
"21:00",
"21:15"
],
"booked_time_slots": [

],
"blocked_time_slots": [
"18:15",
"18:30",
"18:45",
"19:00",
"19:15",
"11:15",
"11:30",
"11:45",
"12:00"
],
"staff_detail": {
    "staffId": "6",
    "fname": "James Keri",
    "image": ""
    }
}

我的Index out of range中的以下代码中出现cellForRow错误:

var arrayOfSlotTime = [String]()
var arrayOfBlockTime = [String]() 
let stringFirst = arrayOfSlotTime[indexPath.row] as? String
let stringSecond = arrayOfBlockTime[indexPath.row] as? String
if stringFirst == stringSecond {
    cell.contentView.backgroundColor = Constant.color.theamColor
} else { 
    cell.contentView.backgroundColor = Constant.color.blue
}

1 个答案:

答案 0 :(得分:1)

你的问题是,你只是在创建两个空数组,而不是试图访问它的元素。

执行此操作时:

var arrayOfSlotTime = [String]()
var arrayOfBlockTime = [String]() 

两个数组的计数都为零,它不包含任何元素。而且比你这个:

let stringFirst = arrayOfSlotTime[indexPath.row] as? String
let stringSecond = arrayOfBlockTime[indexPath.row] as? String

您正尝试将该元素访问为indexPath.row的任何值。但是,您的容器是空的,其中没有元素,因此您会因Index out of range错误而崩溃。

我认为arrayOfSlotTimearrayOfBlockTime应该来自其他地方,并且不应该是空的。

编辑:

如果数组在问题开头包含JSON中的值,请查看文件。 time_slots我假设arrayOfSlotTime有45个项目,而blocked_time_slotsarrayOfBlockTime有8个项目。

当您使用值{8}访问indexPath.row时,arrayOfBlockTime会因Index out of range而崩溃,因为它包含来自[0...7]的元素

如果您想根据两个数组对单元格进行某些转换,并且在给定indexPath处具有相同的值,请执行以下操作:

// Lets create the first string with the rigth indexPath value
let slotTime = arrayOfSlotTime[indexPath.row] as? String ?? ""
// Check if arrayOfBlockTime has the slotTime at the indexPath, and apply the color to a new variable 
let backgroundColor = arrayOfBlockTime.contains(slotTime) ? Constant.color.theamColor : Constant.color.blue
// Assign the background color
cell.contentView.backgroundColor = backgroundColor