好久好久沒寫 Swift,最近在用 Swift 寫一個(gè)項(xiàng)目的時(shí)候,需要排序下通訊錄和分組的诗箍,用了網(wǎng)友的 SCIndexView 索引 和 BMChineseSortSwift 排序 拼音排序后,很輕松了實(shí)現(xiàn)以下效果的
然而發(fā)現(xiàn)使用 BMChineseSortSwift
排序的時(shí)候挽唉,排序不對(duì)滤祖,于是嘗試用 Swift 寫下排序的:
func sortAddressList() {
if (self.dataArray?.count ?? 0 < 1) {
return
}
// 抽取首字母
var resultNames: [String] = [String]()
if let nameArray = self.dataArray?.map({ item -> String? in
if let name = item.realname {
let pinYin: String = name.transformToPinYin()
return pinYin.first?.description ?? ""
} else {
return ""
}
}).compactMap({$0}) {
let nameSet: NSSet = NSSet(array: nameArray)
for item in nameSet {
resultNames.append("\(item)")
}
}
// 排序, 同時(shí)保證特殊字符在最后
resultNames = resultNames.sorted(by: { (one, two) -> Bool in
if (one.isNotLetter()) {
return false
} else if (two.isNotLetter()) {
return true
} else {
return one < two
}
})
// 替換特殊字符
self.firstLetterArray.removeAll()
let special: String = "#"
for value in resultNames {
if (value.isNotLetter()) {
self.firstLetterArray.append(special)
break
} else {
self.firstLetterArray.append(value)
}
}
// 分組
self.sortedModelArr.removeAll()
for object in self.firstLetterArray {
if let people: [AddressListItemModel] = (self.dataArray?.filter { (dataModel) -> Bool in
if let pinYin = dataModel.realname?.transformToPinYin().first?.description {
if (pinYin.isNotLetter() && object == special) {
return true
} else {
return pinYin == object
}
} else {
return false
}
}.compactMap{$0}) {
self.sortedModelArr.append(people)
}
}
var indexArray: [String] = self.firstLetterArray
indexArray.insert(UITableView.indexSearch, at: 0)
self.tableView.sc_indexViewDataSource = indexArray
self.tableView.reloadData()
}
extension String {
func transformToPinYin() ->String {
let mutableString = NSMutableString(string: self)
CFStringTransform(mutableString, nil, kCFStringTransformToLatin, false)
CFStringTransform(mutableString, nil, kCFStringTransformStripDiacritics, false)
let string = String(mutableString)
return string.replacingOccurrences(of: " ", with: "").uppercased()
}
func isNotLetter()-> Bool {
let upperCaseStr: String = self.uppercased()
let c = Character(upperCaseStr)
if c >= "A", c <= "Z"{//
return false
} else {
return true
}
}
}
以上的實(shí)現(xiàn)就是實(shí)現(xiàn),木有用到 Swift 一些優(yōu)雅的寫法和高級(jí)的使用瓶籽,感覺以上代碼吐槽點(diǎn)太多匠童,但是這是前一段時(shí)間第一反應(yīng)寫下來(lái)的,還是記錄下塑顺。
過段時(shí)間后汤求,再回頭看看自己 用 OC 思維寫 Swift 的吐槽點(diǎn)了,也應(yīng)該蠻有趣的