代码之家  ›  专栏  ›  技术社区  ›  Dani iman kazemayni

对实际具有值的可选项展开时为零

  •  1
  • Dani iman kazemayni  · 技术社区  · 7 年前

    我发现了一个非常奇怪的错误,而展开一个可选的。当我打印值时,我实际上可以看到它,但是,它崩溃了,它说:

    致命错误:在展开可选值时意外找到nil

    这是密码( fetchPost() 是在 viewDidLoad() :

    func fetchPost() {
        Api.Posts.observePostIncludingImages(withId: postId) { (post, photosStringArray) in
    
            self.isLiked(postId: post.id!, completion: { boolValue in
                Api.Posts.fetchCount(postId: post.id!, completion: { totalCount in
                    post.isLiked = boolValue
    
                    self.photosArrayString = photosStringArray
                    print(photosStringArray) // prints the actual image string
                    self.setScrollView()
    
                })
            })
        }
    }
    
    func setScrollView() {
        for  i in stride(from: 0, to: photosArrayString.count, by: 1) {
            var frame = CGRect.zero
            frame.origin.x = self.galleryScrollView.frame.size.width * CGFloat(i)
            frame.origin.y = 0
            frame.size = self.galleryScrollView.frame.size
            galleryScrollView.isPagingEnabled = true
    
            let newUIImageView = UIImageView()
            print(photosArrayString[i]) // Prints the value again
            let myImage = UIImage(named: photosArrayString[i])! // CRASHES! i = 0 (first item in the array)
    
            avgBackgroundColorsOfImage.append(myImage.averageColor!)
    
            newUIImageView.image = myImage
            newUIImageView.frame =  frame
    
            newUIImageView.contentMode = UIViewContentMode.scaleAspectFit
    
            newUIImageView.sd_setImage(with: URL(string: self.photosArrayString[i]), completed: nil)
    
    
            galleryScrollView.backgroundColor = avgBackgroundColorsOfImage[i]
            galleryScrollView.addSubview(newUIImageView)
    
            self.galleryScrollView.contentSize = CGSize(width: self.galleryScrollView.frame.size.width * CGFloat(photosArrayString.count),
                                                        height: self.galleryScrollView.frame.size.height)
            pageControl.addTarget(self, action: #selector(changePage), for: UIControlEvents.valueChanged)
        }
    }
    
    1 回复  |  直到 7 年前
        1
  •  3
  •   Connor Neville    7 年前

    你要拆开的东西是可选的 UIImage 你刚刚创造了。数组中保存的任何字符串都是有效的字符串。但是,它不是资产目录中有效图像的名称。注意,错误是关于“展开nil值”,而不是“数组超出边界”-这是不同的事情。

    这个 docs on this initializer 显示它是一个可选的init,返回“指定文件的图像对象,如果方法找不到指定的图像,则返回nil。”