【问题标题】:how to check if file exist use swift, rewrite from objective c如何检查文件是否存在使用swift,从目标c重写
【发布时间】:2015-02-20 06:10:06
【问题描述】:

如何将这个objective-c语言改写成swift?

NSString *filePath = @"/Applications/MySample.app";
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath])
    {
        // avoid open add friend
    }

问候。

【问题讨论】:

标签: ios swift


【解决方案1】:

等效的 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
【解决方案2】:
let path = "/Applications/MySample.app"
let hasFile = FileManager().fileExists(atPath: path)
if hasFile {
    // use file
}
else {
    // possibly inform user the file does not exist
}

【讨论】:

  • 我在downlods 文件夹中手动创建了一个文件。我尝试使用代码let fileDirectory="/Downloads/Receipt Data.txt" if FileManager().fileExists(atPath: fileDirectory) { print("file exists") } else{ print("file does not exist") } 访问该文件,但它总是说“文件不存在”。我很困惑如何提供下载目录。任何人请澄清我的疑问。
【解决方案3】:

在提出问题几年后,我建议按字面意思rewrite 并使用与 URL 相关的 API

let fileURL = URL(fileURLWithPath:"/Applications/MySample.app")
if let _ = try? fileURL.checkResourceIsReachable()  {
   // file exists
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-01
    • 2017-04-24
    • 2014-08-02
    • 2018-01-24
    • 2018-06-21
    • 2013-10-28
    相关资源
    最近更新 更多