如何检查文档目录中是否存在多个文件? (Swift)
How to check if multiple files exist in documents directory? (Swift)
我可以用这个方法检查一个文件是否存在:
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]
写个方法举例
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)
我可以用这个方法检查一个文件是否存在:
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]
写个方法举例
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)