如何从目录将图片添加到数组?解决解包Optional值遇nil的致命错误
修复“Unexpectedly found nil while unwrapping an Optional value”错误
错误原因
崩溃出现在imageArray.append(image!)这一行,因为UIImage(contentsOfFile: imageURL.path)找不到指定路径的图片文件时会返回nil,而你用!强制解包可选值,直接触发了致命错误。
具体修复方案
1. 移除强制解包,用可选绑定安全加载图片
不要直接强制解包image,先判断图片是否成功加载,再添加到数组:
for myIndex in 1...17 { let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true) guard let dirPath = paths.first else { print("无法获取Documents目录路径") continue } let folderURL = URL(fileURLWithPath: dirPath).appendingPathComponent("\(index)") let imageURL = folderURL.appendingPathComponent("\(myIndex).jpg") if let image = UIImage(contentsOfFile: imageURL.path) { imageArray.append(image) } else { print("加载图片失败,路径不存在:\(imageURL.path)") } }
2. 排查路径有效性
- 打印
imageURL.path的实际值,手动检查该路径下是否存在对应编号的.jpg文件 - 确认
index变量的数值是否正确,确保Documents/\(index)这个目录确实存在 - 可以提前判断目录是否存在,避免无效的图片路径拼接:
guard FileManager.default.fileExists(atPath: folderURL.path) else { print("目标目录不存在:\(folderURL.path)") continue }
3. 避免其他潜在的强制解包风险
原代码中dirPath!也是强制解包,改成guard let绑定可以避免Documents目录获取失败时的崩溃。
内容的提问来源于stack exchange,提问作者user25462420
相关产品推荐
相关产品推荐

