pathExtension不可用:改为在NSURL上使用pathExtension。 Swift 2.0

时间:2015-09-18 07:24:00

标签: ios xcode swift swift2

我从文档目录中获取了mp3文件,我写道路径扩展等于" mp3",在它正在运行的Swift 1.2中,但是在Swift 2.0中我得到错误" ' pathExtension'不可用:改为在NSURL上使用pathExtension。"

 func fetchFilesFromFolder() {
        let fileManager = NSFileManager.defaultManager()
        let folderPathURL = fileManager.URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask)[0]
        if let directoryURLs = try? fileManager.contentsOfDirectoryAtURL(folderPathURL, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles) {
            listOfMP3Files = directoryURLs.map(){ $0.lastPathComponent! }.filter(){ $0.pathExtension == "mp3" } // error is here
        }
    }

6 个答案:

答案 0 :(得分:12)

或者你可以使用这个扩展名:

extension String {
    var ns: NSString {
        return self as NSString
    }
    var pathExtension: String {
        return ns.pathExtension
    }
    var lastPathComponent: String {
        return ns.lastPathComponent
    }
}

答案 1 :(得分:4)

Xcode 8.3.2•Swift 3.1

$g_path = "http://my-hostname/demo/mantis";

答案 2 :(得分:4)

根据此link,此扩展程序会在很多情况下为您提供帮助。

extension String {

    var lastPathComponent: String {
        get {
            return (self as NSString).lastPathComponent
        }
    }

    var pathExtension: String {
        get {

            return (self as NSString).pathExtension
        }
    }

    var stringByDeletingLastPathComponent: String {
        get {

            return (self as NSString).stringByDeletingLastPathComponent
        }
    }

    var stringByDeletingPathExtension: String {
        get {

            return (self as NSString).stringByDeletingPathExtension
        }
    }

    var pathComponents: [String] {
        get {

            return (self as NSString).pathComponents
        }
    }

    func stringByAppendingPathComponent(path: String) -> String {

        let nsSt = self as NSString

        return nsSt.stringByAppendingPathComponent(path)
    }

    func stringByAppendingPathExtension(ext: String) -> String? {

        let nsSt = self as NSString

        return nsSt.stringByAppendingPathExtension(ext)
    }
}

答案 3 :(得分:3)

只需更改顺序:首先filter,而不是map。现在,方法pathExtension将应用于NSURL对象。

listOfMP3Files = directoryURLs.filter { $0.pathExtension == "mp3" }.map { $0.lastPathComponent! }

您可以使用filter规则在maptrailing closure之后省略括号。

Apple已从String删除了与路径相关的API,以便选择更合适的URL

答案 4 :(得分:1)

我将Dharmesh和Leo的方法结合起来让我的扩展工作:

scanner.useDelimiter(System.getProperty("line.separator"));

答案 5 :(得分:0)

Swift Doc 1.2 specs regarding these funcs don't return an optional

要使其在Swift 2.0中向后兼容1.2,请执行以下操作:

改进@Dharmesh Kheni的版本。

extension String {
  var ns: NSString {
    return self as NSString
  }
  var pathExtension: String {
    return ns.pathExtension ?? ""
 }
  var lastPathComponent: String {
    return ns.lastPathComponent ?? ""
   }
}