检查文件是否存在于文件名前缀为 Swift 的目录中

Check file exists in directory with prefix of file name in Swift

我想检查我的文件是否存在 SWIFT.

例如

我的文件名是这样的 Companies_12344

所以在 _ 值之后是动态的,但 "Companies_" 是静态的。

我该怎么做?

我已经完成了下面的拆分文件名代码

我如何通过 NSFileManager 检查 "Companies_"

是否存在文件名

下面是我的代码 For split

 func splitFilename(str: String) -> (name: String, ext: String)? {
    if let rDotIdx = find(reverse(str), "_")
    {
        let dotIdx = advance(str.endIndex, -rDotIdx)
        let fname = str[str.startIndex..<advance(dotIdx, -1)]
        println("splitFilename >> Split File Name >>\(fname)")
    }


    return nil
}

我认为您需要此代码:

let str = "Companies_12344"

if str.hasPrefix("Companies") {
    println("Yes, this one has 'Companies' as a prefix")
    let compos = str.componentsSeparatedByString("_")
    if let file = compos.first {

        println("There was a code after the prefix: \(file)")
        var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String

        var yourPath = paths.stringByAppendingPathComponent("\(file)_")

        var checkValidation = NSFileManager.defaultManager()

        if (checkValidation.fileExistsAtPath(yourPath))
        {
            println("FILE AVAILABLE");
        }
        else
        {
            println("FILE NOT AVAILABLE");
        }
    }
}