我使用此代码将图像附加到目录中的数组中
for myIndex in 1...17 {
let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
let dirPath = paths.first
let imageURL = URL(fileURLWithPath: dirPath!).appendingPathComponent("\(index)/\(myIndex).jpg")
let image = UIImage(contentsOfFile: imageURL.path)
imageArray.append(image!)
}
但是我有这个错误:
线程 1:致命错误:在解包时意外发现 nil 可选值
在这一行中:
imageArray.append(image!)
如何解决?
这很清楚。在
image
的情况下,您将使用 !
强制展开 nil
。所以,我认为你应该:
if let
或guard let
:if let image = UIImage(contentsOfFile: imageURL.path) {
imageArray.append(image) //without "!"
}