如何检查文件是否存在使用swift,从目标c重写

时间:2014-12-22 06:41:59

标签: ios swift

如何将这个Objective-c语言重写为swift?

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

问候。

3 个答案:

答案 0 :(得分:9)

等效Swift 3代码:

let filePath = "/Applications/MySample.app"
if (FileManager.default.fileExists(atPath: filePath)) {
    // avoid open add friend
}

Swift 2

let filePath = "/Applications/MySample.app"
if (NSFileManager.defaultManager().fileExistsAtPath(filePath))
{
    // avoid open add friend
}

答案 1 :(得分:1)

问题问题几年后,我建议按字面意思重写重写并使用与网址相关的API

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

答案 2 :(得分:0)

let path = "/Applications/MySample.app"
let hasFile = FileManager().fileExists(atPath: path)
if hasFile {
    // use file
}
else {
    // possibly inform user the file does not exist
}