gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 10:21:05 25 4
gpt4 key购买 nike

在函数中,我检索目录列表。我想让该函数接受一个过滤器参数,以便在返回目录之前过滤检索。

这是我的功能:

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]()
}
}

最后,我想这样调用函数:

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

允许这样做的过滤器参数类型是什么?

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

public func getDocumentPaths() -> [String] {
// Get the directory contents including folders
guard let directoryUrls = try? NSFileManager.defaultManager().contentsOfDirectoryAtURL(NSURL(string:"")!, includingPropertiesForKeys: nil, options: []) else {
// Failed so return empty list
return [String]()
}

return directoryUrls.map { $0.path! }
}

最佳答案

如果你想在 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方法

关于swift - 将过滤器作为参数传递给 Swift 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34932890/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com