Ios 如何将URL数组转换为字符串数组?

Ios 如何将URL数组转换为字符串数组?,ios,swift,Ios,Swift,我有几个本地保存的.txt文件,它们被加载并保存为URL数组,如: func loadShortStories() { shortStories = Bundle.main.urls(forResourcesWithExtension: "txt", subdirectory: nil)! } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let destinationViewCont

我有几个本地保存的.txt文件,它们被加载并保存为URL数组,如:

func loadShortStories() {
    shortStories = Bundle.main.urls(forResourcesWithExtension: "txt", subdirectory: nil)!
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destinationViewController = segue.destination as? ListVC {
        destinationViewController.shortStories = shortStories
    }
}
然后在下一个列表VC中,我将它们加载到tableview中,我有:

var shortStories: [URL] = []
我需要硬编码.txt文件的特定顺序,但需要先将它们转换为字符串。我该怎么做

我试过了

let shortStoriesString = shortStories.absoluteString but it does not work.
增加:

我确实使用以下方法删除cellForRowAt方法中的pathextension和lastcomponent:

shortStories[indexPath.row].deletingPathExtension().lastPathComponent
但在此之前,我想硬编码.txt文件加载到textview的顺序,因为它是随机的,我希望它们以特定的非算法方式列出,如:

let order : [String] = [ "story7.txt", "story3.txt", "story1.txt", "story4.txt" ]
。这就是我试图将URL转换为字符串的原因。

您可以尝试

let shortStoriesString = shortStories.map {$0.lastPathComponent} 

由于
短篇小说
是一个数组而不是单个对象

如果您已经知道文件名,请使用它生成url

let stories: [String] = [ "story7", "story3", "story1", "story4" ]

let storyURL = Bundle.main.url(forResource: stories[index], withExtension: "txt")

我不确定,但OP可能不想在他的表视图中显示整个文件url。最好只显示url lastPathComponent或获取
.nameKey
的fileURL资源值。对于那些以前没有使用过map的人来说,这是一种将一个数组逐个元素转换为另一个数组的方法。在这个例子中,每个元素都被转换为在同一个元素上调用
.absoluteString
的结果。@LeoDabus我认为这个解决方案是可行的。OP写道,他们需要将“URL数组”转换为“字符串数组”,这肯定是第一步。为什么不直接传递URL数组本身呢?看看这个问题,我希望它们以特定的非算法方式列出,比如:
let order:[string]=[“story7.txt”、“story3.txt”、“story1.txt”、“story4.txt”]
本地保存是什么意思?这些文件位于哪里?在我的应用程序包中,我不会将您的URL数组转换为字符串数组。保留URL并在填充表视图时使用它们。关于您的文件名,您可以使用
FileManager.default.displayName(atPath:yourURL.path)
或获取LocalizedNameKey的url资源值。FileManager.default.displayName(atPath:yourURL.path)让我为tableView硬编码.txt文件的顺序?你能给我举一个如何写这个的例子吗?我以前从未见过这个。您可以使用url lastPathComponent或displayName自定义url排序
url.sorted{$0.lastPathComponent<$1.lastPathComponent}
url.sorted{FileManager.default.displayName(atPath:$0.path)
谢谢。我刚刚尝试了这个方法,但得到了一个错误-无法将类型为“(Any)->Int”的值转换为预期的参数类型“(unbounddrange)->()”