我试图了解我最近遇到的一些代码。
在此处https://stackoverflow.com/a/51173170/1162328的一个问题的答案中,当在documentDirectory中循环访问文件时,作者使用了带有格式说明符的String。任何人都可以对%@/%@
的实际情况有所了解吗?
for fileName in fileNames {
let tempPath = String(format: "%@/%@", path, fileName)
// Check for specific file which you don't want to delete. For me .sqlite files
if !tempPath.contains(".sql") {
try fileManager.removeItem(atPath: tempPath)
}
}
阅读Apple documentation archive for Formatting Basics时遇到了这个问题:
在格式字符串中,'%'字符会声明一个值的占位符,后面的字符将确定预期值的类型以及如何设置其格式。例如,格式字符串“%d house”期望用整数值代替格式表达式“%d”。 NSString支持为ANSI C functionprintf()定义的格式字符,并为任何对象加上“ @”。
然后%@/%@
到底在做什么?
%@
与%d
类似或类似。这是Swift中字符串插值的方法。
确切地说,%@
是对象的占位符-在Objective-C LOT中使用。由于NSString *
是对象(现在只是String),因此用于将NSString *
插入另一个NSString *
。
也给定的代码只是重写的objective-c代码,类似于
NSString *tempPath = [NSString stringWithFormat:@"%@/%@", path, filename];
可以快速重写:
let tempPath = path + "/" + fileName
此外,给定路径=“ Test”和fileName =“ great”将给出输出Test / great。
另外一个提示:%@一样危险。您可以将UITableView以及String放入其中。它将使用description属性插入字符串。
每个格式说明符由以下参数之一替换(通常可以相同的顺序,尽管可以通过位置参数进行控制)。因此,在您的情况下,第一个%@
被替换为path
,第二个%@
被替换为fileName
。示例:
let path = "/path/to/dir"
let fileName = "foo.txt"
let tempPath = String(format: "%@/%@", path, fileName)
print(tempPath) // /path/to/dir/foo.txt
构建文件名和路径的首选方法是使用相应的URL
方法而不是字符串操作。示例:
let pathURL = URL(fileURLWithPath: path)
let tempURL = pathURL.appendingPathComponent(fileName)
if tempURL.pathExtension != "sql" {
try FileManager.default.removeItem(at: tempURL)
}