Set 不是表视图数据源的好选择。 Dictionary 也不是一个好的选择。两者都是无序的集合,表视图的数据源需要一个明确的顺序。我建议将源数组分解为数组数组,其中每个子数组包含以特定字母开头的所有单词,按字母顺序排序。执行此操作的代码可能如下所示:
import UIKit
let strings = ["arf",
"woofing",
"flounder",
"Manbaby",
"Dogs",
"baseballs",
"Suet",
"Cards",
"Tiny-fingered, cheeto-faced, ferret-wearing sh*tgibbon",
"apple",
"Acorn",
"Achy-breaky heart",
"songbirds",
"Aces"]
let aValue = "a".unicodeScalars.first!.value
let zValue = "z".unicodeScalars.first!.value
var result = [[String]]()
for value in aValue...zValue {
let aChar = Character(UnicodeScalar(value)!)
let thisArray = strings
.filter{$0.lowercased().characters.first! == aChar}
.sorted{$0.caseInsensitiveCompare($1) == .orderedAscending}
if !thisArray.isEmpty {
result.append(thisArray)
}
}
result.forEach{print($0)}
产生以下输出:
["Aces", "Achy-breaky heart", "Acorn", "apple", "arf"]
["baseballs"]
["Cards"]
["Dogs"]
["flounder"]
["Manbaby"]
["songbirds", "Suet"]
["Tiny-fingered, cheeto-faced, ferret-wearing sh*tgibbon"]
["woofing"]
如果您想要一个包含每个字母条目的数组,即使没有以该字母开头的单词,也可以去掉if !thisArray.isEmpty 测试。