swift - 展开可选绑定(bind) fatal error

标签 swift xcode6

我正在使用最新稳定的 Swift 在我的函数中,当我运行我的 ios 应用程序时,我收到 fatal error

"fatal error: unexpectedly found nil while unwrapping an Optional value".

我寻找答案,但他们提供了不同的解包方法。

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        var cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! UICollectionViewCell
        var imageView = cell.viewWithTag(1) as! UIImageView
        imageView.image = UIImage(named: imagesArray[indexPath.row])
        }

最佳答案

您可以使用 if let block 来确保在尝试使用该值之前不为 nil

if let imageView = cell.viewWithTag(1) as? UIImageView {
    imageView.image = UIImage(named: imagesArray[indexPath.row])
}

关于swift - 展开可选绑定(bind) fatal error ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30808370/

相关文章:

swift - Xcode 6.1 标题文本属性

swift - UIAlertViewController 中的文本字段具有圆角矩形边框样式。 ( swift )

ios - 无论我将构建版本或应用程序版本更改为什么,都会出现 ITEMS-4238 "Redundant Binary Upload"错误

swift - 自定义 UIViewControllerAnimatedTransitioning 完成后显示黑屏

swift - 在 Swift 中附加两个键路径

ios - 按下按钮时出现 Xcode 奇怪错误

ios - 我的预发行版应用程序在 iTunes Connect 中已超过一周为 "processing",这是怎么回事?

swift - 如何在 Swift 中将复选框的状态保存到核心数据?

ios - SwiftUI 内的 UITextView View 背景和深色模式的边框颜色(表单)

ios - 导出到 xliff 时,Xcode6 不导出 header 中定义的 NSLocalizedStrings()