arrays - 解开一个实际有值的可选时为零

标签 arrays swift xcode

我在解包可选时遇到了一个非常奇怪的错误。当我打印该值时,我实际上可以看到它,但它崩溃了,并显示:

Fatal error: Unexpectedly found nil while unwrapping an Optional value

这是代码(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)
    }
}

最佳答案

您要展开的是您刚刚创建的可选 UIImage。数组中保存的任何字符串都是有效字符串。但是,它不是 Assets 目录中有效图像的名称。请注意错误是关于“解包一个 nil 值”,而不是“数组越界”——它们是不同的东西。

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

关于arrays - 解开一个实际有值的可选时为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51679061/

相关文章:

java - 从Java中的多维数组中删除项目

将日期数组转换为整数

python - 将 Python NumPy 数组插入 PostgreSQL 数据库

ios - 调用 plist 的子项

ios - 如何正确检查应用程序连接?

swift - 如何在运行时确定泛型变量的值?

xcode - 如何将自定义的 cocoa 框架嵌入到 mac os x 应用程序中?

C# 多维数组

swift - Ios 开发 Swift 类和子类

ios - 如何将数据从 ViewDidLoad 传递到按钮的函数