Swift 从macOS目录读取元素数组

Swift 从macOS目录读取元素数组,swift,macos,swift4,Swift,Macos,Swift4,我可以通过以下方式读取Xcode项目中上传的元素(图像或视频): let photos = (1...9).map { NSImage(named: NSImage.Name(rawValue: "000\($0)")) } 或者像这样: let videos = (1...100).map { _ in Bundle.main.urls(forResourcesWithExtension: "mov", subdirectory: nil)![Int(arc4random_u

我可以通过以下方式读取Xcode项目中上传的元素(图像或视频):

let photos = (1...9).map {
    NSImage(named: NSImage.Name(rawValue: "000\($0)"))
}
或者像这样:

let videos = (1...100).map { _ in
    Bundle.main.urls(forResourcesWithExtension: "mov", subdirectory: nil)![Int(arc4random_uniform(UInt32(100)))]
}
但是如何使用
.map
方法从macOS目录中读取文件(作为数组)

/Users/me/Desktop/ArrayOfElements/

首先,第二种方法非常昂贵,电影URL数组从捆绑包中读取了100次。这更有效:

let resources = Bundle.main.urls(forResourcesWithExtension: "mov", subdirectory: nil)!
let videos = (1...100).map { _ in
    resources[Int(arc4random_uniform(100))]
}
只有当应用程序不是沙盒时,才能从
/Users/me/Desktop
读取,否则只能从应用程序容器读取

要从目录中获取所有文件(如
[URL]
),请使用
FileManager

let url = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Desktop/ArrayOfElements")
do {
    let fileURLs = try FileManager.default.contentsOfDirectory(at: url, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
    let movieURLs = fileURLs.filter{ $0.pathExtension == "mov" }
    print(movieURLs)
} catch { print(error) }

与使用
map
相比,我建议实现一个好,您如何访问
/Users/me/Desktop/A/Singe/File.txt
?让url=url(fileURLWithPath:“/Users/me/Desktop/A/Single/File.txt”)好。现在,如何给定一个
n:Int=123
,您将如何使用
n
访问
/Users/me/Desktop/A/Single/File123.txt
?这就是我的问题所在!我的意思是对于
n=123
的特定情况。您如何将int
123
放在该路径中,以便从中初始化
URL
?非常感谢,@vadian。但是如何使用FileManager使用
.reversed()
方法呢?结果是一个数组。您可以使用数组响应的任何函数,包括
。反转
将其放置在何处?这对我来说是不熟悉的语法。在
FileManager
行的末尾
…选项:[.skipsHiddenFiles])。reversed()
该死!(非常感谢!)