【问题标题】:What is the relevance of this String format specifier?这个字符串格式说明符的相关性是什么?
【发布时间】: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


【解决方案1】:

每个格式说明符都被以下参数之一替换(通常以相同的顺序,尽管可以使用位置参数来控制)。所以在你的情况下,第一个%@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)
}

【讨论】:

    【解决方案2】:

    %@ 类似于%d 或类似的东西。这就是 Swift 中字符串插值的方式。

    确切地说,%@ 是对象的占位符 - 在 Objective-C 中经常使用。由于NSString * 是对象(现在它只是字符串),它被用来将NSString * 插入另一个NSString *

    另外给出的代码只是重写了objective-c代码,类似于

    NSString *tempPath = [NSString stringWithFormat:@"%@/%@", path, filename];
    

    可以用swift重写:

    let tempPath = path + "/" + fileName
    

    另外,给定 path = "Test" 和 fileName = "great" 将给出输出 Test/great。

    还有一点:%@ 既危险又好。您可以将 UITableView 以及 String 放入其中。它将使用描述属性插入字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-04
      • 2013-06-22
      • 2013-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多