我正在编写一个func来编辑Users/johnDoe目录中的文本文件.
let filename = "random.txt"
let filePath = "/Users/johnDoe"
let replacementText = "random bits of text"
do {
try replacementText.write(toFile: filePath, atomically: true, encoding: .utf8)
}catch let error as NSError {
print(error: + error.localizedDescription)
}
Run Code Online (Sandbox Code Playgroud)
但我希望能够拥有普遍的道路.就像是
let fileManager = FileManager.default
let downloadsURL = FileManager.default.urls(for: .downloadsDirectory, in: .userDomainMask).first! as NSURL
let downloadsPath = downloadsURL.path
Run Code Online (Sandbox Code Playgroud)
但对于JohnDoe文件夹.我无法找到有关如何执行此操作的任何文档.我能找到的最接近的东西是使用NSHomeDirectory().而且我不确定如何在这种情况下使用它.
当我尝试添加它...
let fileManager = FileManager.default
let downloadsURL = FileManager.default.urls(for: NSHomeDirectory, in: .userDomainMask).first! as NSURL
let downloadsPath = downloadsURL.path
Run Code Online (Sandbox Code Playgroud)
我收到一个错误:
"无法将'String'类型的值转换为预期的参数类型'FileManager.SearchPathDirectory'"
我试过了.NSHomeDirectory,.NSHomeDirectory(),NShomeDirectory,NShomeDirectory()