在我的swift
应用中,我有一段代码:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "hashtagCell", for: indexPath) as! HashtagCollectionViewCell
if let hashtagName:String = self.suggestedHashtags[(indexPath as NSIndexPath).item] as? String {
cell.hashtagName.text = hashtagName
} else {
cell.hashtagName.text = "emptyHashtag"
}
cell.hashtagName.textColor = UIColor.lightGray
cell.hashtagName.font = font
return cell
}
和这一行:
if let hashtagName:String = self.suggestedHashtags[(indexPath as NSIndexPath).item] as? String
有时会因以下错误导致我的应用崩溃:
libc++abi.dylib: terminating with uncaught exception of type NSException
我认为if let
应该处理这个问题,但似乎没有。这可能是什么问题?
答案 0 :(得分:2)
您的例外很可能超出范围。如果您的阵列可能不够大,无法处理所有项目,则需要检查。像这样的东西会起作用:
cell.hashtagName.text = "emptyHashtag"
if indexPath.item < suggestedHashtags.count {
if let hashtagName = suggestedHashtags[indexPath.item] as? String {
cell.hashtagName.text = hashtagName
}
}