Arrays 在展开实际具有值的可选项时为Nil
我在打开一个可选文件时遇到了一个非常奇怪的错误。当我打印值时,我实际上可以看到它,但它崩溃了,它说: 致命错误:在展开可选值时意外发现nil 下面是代码(Arrays 在展开实际具有值的可选项时为Nil,arrays,swift,xcode,Arrays,Swift,Xcode,我在打开一个可选文件时遇到了一个非常奇怪的错误。当我打印值时,我实际上可以看到它,但它崩溃了,它说: 致命错误:在展开可选值时意外发现nil 下面是代码(fetchPost()在viewDidLoad()中调用): 您要展开的内容是刚刚创建的可选UIImage。数组中包含的任何字符串都是有效字符串。但是,它不是资产目录中有效图像的名称。请注意,错误是关于“展开零值”,而不是“数组超出边界”-这些是不同的内容 显示它是一个可选的init,返回“指定文件的图像对象,如果该方法找不到指定的图像,则返回
fetchPost()
在viewDidLoad()中调用):
您要展开的内容是刚刚创建的可选UIImage
。数组中包含的任何字符串都是有效字符串。但是,它不是资产目录中有效图像的名称。请注意,错误是关于“展开零值”,而不是“数组超出边界”-这些是不同的内容
显示它是一个可选的init,返回“指定文件的图像对象,如果该方法找不到指定的图像,则返回nil。”这解释了很多。谢谢,可以,但等待时间很长,它现在显示为2分钟。我接受:)
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)
}
}