我试图接受一大群人(现在只用名字简化),不仅要对它进行排序,还要在所有以这封信开头的人面前添加第一个字母。
基本上这个:[" Daniel"," Michael"," Lisa"," Lena"]应该成为:[&# 34; D"," Daniel"," L"," Lena"," Lisa"," M&#34 ;," Michael"]
我有一些在操场上工作的东西,但对我来说这看起来很丑陋,如果人们成千上万或者更多的话就不知道表现。
//: Playground - noun: a place where people can play
import Cocoa
var previousName: String?
let people = ["Martin", "Michael", "Lisa", "Lena", "Dirk"]
var peopleWithLetters: [String] = []
people.sorted { $0.localizedCaseInsensitiveCompare($1) == ComparisonResult.orderedAscending }.forEach {
if $0.uppercased().characters.first! != previousName?.uppercased().characters.first! {
peopleWithLetters.append("\($0.uppercased().characters.first!)")
}
previousName = $0
peopleWithLetters.append($0)
}
任何想法如何简化或遵循最佳实践都将受到高度赞赏。
答案 0 :(得分:0)
这是函数式编程的完美用例。
以下是代码:
//: Playground - noun: a place where people can play
func addSections(in words: [String]) -> [String] {
let sections = Set(words.map { String($0[$0.startIndex]) })
let wordsWithSections = words + sections
return wordsWithSections.sorted { $0 < $1 }
}
let names = ["Daniel", "Michael", "Lisa", "Lena"]
addSections(in: names)
虽然如果您计划使用此数组来提供tableView(部分/行),您最好使用您在评论中提到的字典。