【发布时间】:2015-02-20 06:10:06
【问题描述】:
如何将这个objective-c语言改写成swift?
NSString *filePath = @"/Applications/MySample.app";
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
// avoid open add friend
}
问候。
【问题讨论】:
如何将这个objective-c语言改写成swift?
NSString *filePath = @"/Applications/MySample.app";
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
// avoid open add friend
}
问候。
【问题讨论】:
等效的 Swift 3 代码:
let filePath = "/Applications/MySample.app"
if (FileManager.default.fileExists(atPath: filePath)) {
// avoid open add friend
}
斯威夫特 2
let filePath = "/Applications/MySample.app"
if (NSFileManager.defaultManager().fileExistsAtPath(filePath))
{
// avoid open add friend
}
【讨论】:
filepath 更改为常量let
let path = "/Applications/MySample.app"
let hasFile = FileManager().fileExists(atPath: path)
if hasFile {
// use file
}
else {
// possibly inform user the file does not exist
}
【讨论】:
let fileDirectory="/Downloads/Receipt Data.txt" if FileManager().fileExists(atPath: fileDirectory) { print("file exists") } else{ print("file does not exist") } 访问该文件,但它总是说“文件不存在”。我很困惑如何提供下载目录。任何人请澄清我的疑问。
在提出问题几年后,我建议按字面意思rewrite 并使用与 URL 相关的 API
let fileURL = URL(fileURLWithPath:"/Applications/MySample.app")
if let _ = try? fileURL.checkResourceIsReachable() {
// file exists
}
【讨论】: