我有一个包含歌曲标题列表的变量:
var songTitles = ["Song Title 1", "Song Title 2", "Song Title 3"]
我还有歌曲作者的变量
var songAuthors = ["Song Author 1", "Song Author 2", "Song Author 3"]
每当视图加载时,我都会排序" songTitles"按字母顺序这样
override func viewDidLoad() {
super.viewDidLoad()
songTitles.sorted(by: { $0 < $1 })
songTitles.sort()
}
最后但并非最不重要的是,我有一个带有字幕单元格的表视图。 songTitle等于单元格的标题。 songAuthor等于副标题。 排序标题效果很好,但songAuthor与songTitle不匹配。就像说这首歌是Hello,作者是AHAH,还有一首名叫Bye和作者Lala的歌。
表格视图将显示:
SONG TITLE - Bye SONG AUTHOR - AHAH
SONG TITLE - Hello SONG AUTHOr - LALA
基本上,相应的作者与正确的歌曲不匹配。我该如何解决这个问题?
答案 0 :(得分:2)
您可以通过不使用并行数组来解决此问题:
Song
Song
个对象现在,您可以在表格视图中使用Song
个对象,并根据需要显示其属性。
class Song : CustomStringConvertible {
let title:String
let author:String
init(title:String, author:String) {
self.title = title
self.author = author
}
var description : String {
return "\(title) \(author)"
}
}
var songs = [
Song(title: "Song Title 3", author: "Song Author 3")
, Song(title: "Song Title 2", author: "Song Author 2")
, Song(title: "Song Title 1", author: "Song Author 1")
]
songs.sort() {$0.author < $1.author}
print(songs)