【发布时间】:2020-01-18 20:40:38
【问题描述】:
我正在尝试了解我最近遇到的一些代码。
在回答https://stackoverflow.com/a/51173170/1162328 的问题时,作者在遍历documentDirectory 中的文件时使用了带有格式说明符的字符串。任何人都可以了解%@/%@ 实际在做什么吗?
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 房屋”的格式字符串需要一个整数值来替换格式表达式“%d”。 NSString 支持为 ANSI C 函数 printf() 定义的格式字符,以及任何对象的“@”。
那么,%@/%@ 到底在做什么?
【问题讨论】:
-
%@在 Swift 中与插值相同。let tempPath = "\(path)/\(fileName)" -
不要使用这个答案。
String(format: "%@/%@", path, fileName)不是任何有经验的 swift 开发人员会写这个的。字符串连接 (path + filename) 或插值 ("\(path)/\(filename))是更合理的连接字符串的方法。但更重要的是,您不应该使用字符串来模拟 URL 所用的路径/url,它已经有一个美妙的appendingPathComponentAPI。
标签: swift string format-specifiers