我可以使用此方法检查是否存在一个文件:
let fileNameOne = "savedpicture1"
let fileURLOne = documentsDirectoryURL.appendingPathComponent(fileNameOne)
if !FileManager.default.fileExists(atPath: fileURLOne.path) {
removeImage(itemName: "savedpicture1", fileExtension: "jpg")
} else {
print("There was no image to remove")
}
我的问题是不得不为多个文件重复相同的代码行。例如,我想检查文件是否存在于路径数组中,但我必须为每个文件重复上面的代码,这似乎太多余了。我想知道是否有办法检查多个文件而不是重复每个单独路径的代码。 “.fileExists”只允许我检查一条路径:
let filePaths = [fileURLOne.path, fileURLTwo.path, fileURLThree.path,
fileURLFour.path]
答案 0 :(得分:2)
编写一个方法,例如
func checkFiles(with fileNames: [String] {
for fileName in fileNames {
let fileURL = documentsDirectoryURL.appendingPathComponent(fileName)
if !FileManager.default.fileExists(atPath: fileURL.path) {
removeImage(itemName: fileName, fileExtension: "jpg")
} else {
print("There was no image to remove at", fileURL)
}
}
}
并将其命名为
let fileNames = ["savedpicture1", "savedpicture2", "savedpicture3", "savedpicture4"]
checkFiles(with: fileNames)