gpt4 book ai didi

swift - 从 macOS 目录中读取元素数组

转载 作者:行者123 更新时间:2023-11-28 14:54:27 25 4
gpt4 key购买 nike

我可以通过这种方式读取在 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 数组从包中读取了一百次。这样效率更高:

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 来实现 Array extension adding shuffle()

关于swift - 从 macOS 目录中读取元素数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49499636/

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