How to fix: Fatal error: Index out of range

How to fix: Fatal error: Index out of range

我正在尝试使用 swifts .prefix

将我的 [String] 数组限制为只有五个值

首先我使用原始数组 items 并使用 .prefix

拼接它
let testSlice = Array(items.prefix(5))
let newArray = Array(testSlice)

然后我用打印行验证数组只包含五个值。

print("DEV: newArray value: \(newArray)")

if newArray != [] {
    cell.profilePicture.playPortalProfilePic(forImageId: newArray[indexPath.item], { error in
        if let error = error {
            print("Error requesting profile pic: \(String(describing: error))")
        }
    })
} else {
    print("items array was empty, value: \(items)")
}

newArray 然后被传递到我用来请求 profilePictures 的 SDK 提供的方法。 newArray 保存这些值,因此 [indexPath.item] 在这里是合适的。当它正常运行时,它会根据数组中有多少个值在集合视图中创建单元格。

当此行尝试 运行 cell.profilePicture.playPortalProfilePic(forImageId: newArray[indexPath.item]

时,我目前看到 Fatal error: Index out of range

编辑:评论要求的代码

 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.items.count
    }

cell.profilePicture.playPortalProfilePic(forImageId: newArray[indexPath.item]行的完整方法

 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! MyCollectionViewCell

        cell.profilePicture.layer.masksToBounds = true

        let testSlice = Array(items.prefix(5))
        let newArray = Array(testSlice)

        print("DEV: newArray value: \(newArray)")

        if newArray != [] {
            cell.profilePicture.playPortalProfilePic(forImageId: newArray[indexPath.item], { error in
                if let error = error {
                    print("Error requesting profile pic: \(String(describing: error))")
                }
            }
            )
        } else {
            print("items array was empty, value: \(items)")
        }


        cell.backgroundColor = UIColor.cyan
        cell.layer.borderColor = UIColor.black.cgColor
        cell.layer.borderWidth = 1
        cell.layer.cornerRadius = 8

        return cell
    }

您在 numberOfItemsInSection 中使用 items 作为数据源,而在 cellForItemAt 中使用另一个 newArray,大小小于 prefix(5) 因此崩溃,所以你应该 return numberOfItemsInSectionnewArrray.count 的计数或单独使用 testSlice