Ios 如何比较两个不同大小的数组,并根据比较结果在UICollectionviewcell中指定颜色?

Ios 如何比较两个不同大小的数组,并根据比较结果在UICollectionviewcell中指定颜色?,ios,arrays,uitableview,swift3,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",

我必须相互比较下面的阵列。但是我在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": ""
    }
}
我在我的
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
}

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

执行此操作时:

var arrayOfSlotTime = [String]()
var arrayOfBlockTime = [String]() 
两个数组的计数均为零,不包含任何元素。当你这样做的时候:

let stringFirst = arrayOfSlotTime[indexPath.row] as? String
let stringSecond = arrayOfBlockTime[indexPath.row] as? String
您正试图访问元素以访问
indexPath.row
的任何值。但是,您的容器是空的,其中没有任何元素,因此您会因
索引超出范围
错误而崩溃

我假设
arrayOfSlotTime
arrayOfBlockTime
应该来自其他地方,并且肯定不应该为空

编辑:

如果数组包含问题开头的JSON中的值,只需查看文件<代码>时隙我假设is
arrayOfSlotTime
有45项,而
blocked\u时隙
is
arrayOfBlockTime
有8项

当访问值为8的
indexath.row
时,
arrayOfBlockTime
崩溃,索引超出范围,因为它包含
[0…7]中的元素

如果要基于两个数组在给定的
indepath
上具有相同值的单元格进行转换,请执行以下操作:

// 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

你用cellForRow方法做什么?请共享tableViewDataSource。您已经有了答案。当阵列的大小不同时,您无法对其进行比较。任何备选阵列都将是一种攻击,需要格外小心。请在答案中添加
cellForRow
和for循环代码作为编辑,如果可能,请突出显示出错的行!不,不,我只是举个例子,注释空间更少。所以我想任何人都可以想象在数组中的给定值。“时隙”:[]=arrayOfSlotTime和“阻塞时隙”:[]=arrayOfBlockTime有那个值。谢谢danee,我得到了我的答案。我得到了三个不同数组的颜色。