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

时间:2018-08-21 00:46:15

标签: ios swift

我有几个本地保存的.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
    }
}

然后在下一个将它们加载到表格视图的ListVC中,我有:

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转换为字符串。

2 个答案:

答案 0 :(得分:1)

您可以尝试

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

shortStories是一个数组,而不是单个对象

答案 1 :(得分:0)

如果您已经知道文件的名称,请使用它来生成URL。

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

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