我试图使用swift .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]在这里是合适的。当此功能正常运行时,它会根据数组中有多少个值在集合视图中创建单元格。
此行尝试运行Fatal error: Index out of range
时,我目前看到cell.profilePicture.playPortalProfilePic(forImageId: newArray[indexPath.item]
编辑:注释请求的代码
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
}
答案 0 :(得分:0)
您将items
用作numberOfItemsInSection
中的数据源,而在cellForItemAt
内使用另一个newArray
较小的prefix(5)
因此会导致崩溃,因此您应该在newArrray.count
内返回numberOfItemsInSection
的计数或单独使用testSlice