我发现了一个非常奇怪的错误,而展开一个可选的。当我打印值时,我实际上可以看到它,但是,它崩溃了,它说:
致命错误:在展开可选值时意外找到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)
}
}