将过滤器传递给Swift函数作为参数?

时间:2016-01-21 19:43:40

标签: swift swift2 closures

在函数中,我检索目录列表。我想允许函数接受一个filter参数来在返回目录之前过滤检索。

这是我的功能:

x

最后,我想把这个函数称为:

public func getDocumentPaths(filter: ???? = nil) -> [String] {
    do {
        var directoryUrls = try NSFileManager.defaultManager().contentsOfDirectoryAtURL(...)

        // TODO: Filter the directory contents if applicable
        if filter != nil {
            directoryUrls = directoryUrls.filter(filter)
        }

        return directoryUrls.map { $0.absoluteString }
    } catch let error as NSError {
        return [String]()
    }
}

允许此操作的过滤器参数类型是什么?

更新:基于@phimage's suggestion,我使上述功能更像Swift 2.0。更重要的是,FileKit看起来很棒!

getDocumentPaths()
getDocumentPaths { $0.pathExtension == "mp3" }

1 个答案:

答案 0 :(得分:4)

如果您想过滤NSURL

func getDocumentPaths(filter: ((NSURL) -> Bool)? = nil) -> [String] {
    do {
        var directoryUrls = try NSFileManager.defaultManager().contentsOfDirectoryAtURL(NSURL(string:"")!, includingPropertiesForKeys: nil, options: [])   //contentsOfDirectoryAtURL(NSURL(string:"")!)

        // Filter the directory contents if applicable
        if let f = filter {
            directoryUrls = directoryUrls.filter(f)
        }

        return directoryUrls.map { $0.path }
    } catch {
        return [String]()
    }
}

如果要过滤绝对字符串

func getDocumentPaths(filter: ((String) -> Bool)? = nil) -> [String] {
    do {
        var directoryUrls = try NSFileManager.defaultManager().contentsOfDirectoryAtURL...


        var directoryStrings = directoryUrls.map { $0.path }
        // Filter the directory contents if applicable
        if let f = filter {
            directoryStrings = directoryStrings.filter(f)
        }

        return directoryStrings
    } catch {
        return [String]()
    }
}

ps:记录或重新抛出异常

ps2:您可以使用像FileKit这样的库轻松管理文件,有find方法