在开发过程中特别是做通讯录一类功能时经常要用到 中文转换拼音
以及 中文数组排序
,下面记录一下方法,方便以后查看,有需要的可以收藏一下。
中文转换拼音
只需要为 String
类写一个扩展即可,下面方法全部写在 extension String { }
中。
func isIncludeChinese() -> Bool { for ch in self.unicodeScalars { if (0x4e00 < ch.value && ch.value < 0x9fff) { return true } } return false }
|
"张三".isIncludeChinese() "zhangsan".isIncludeChinese()
|
func transformToPinyin(hasBlank: Bool = false) -> String { let stringRef = NSMutableString(string: self) as CFMutableString CFStringTransform(stringRef,nil, kCFStringTransformToLatin, false) CFStringTransform(stringRef, nil, kCFStringTransformStripCombiningMarks, false) let pinyin = stringRef as String return hasBlank ? pinyin : pinyin.replacingOccurrences(of: " ", with: "") }
|
"张三".transformToPinyin() "张三".transformToPinyin(hasBlank: true)
|
func transformToPinyinHead(lowercased: Bool = false) -> String { let pinyin = self.transformToPinyin(hasBlank: true).capitalized var headPinyinStr = "" for ch in pinyin.characters { if ch <= "Z" && ch >= "A" { headPinyinStr.append(ch) } } return lowercased ? headPinyinStr.lowercased() : headPinyinStr }
|
"张三".transformToPinyinHead() "张三".transformToPinyinHead(lowercased: true)
|
中文数组排序
只需要为 Array
类写一个扩展即可,必须为 Array<String>
类型才能排序。
extension Array {
func sortedByPinyin(ascending: Bool = true) -> Array<String>? { if self is Array<String> { return (self as! Array<String>).sorted { (value1, value2) -> Bool in let pinyin1 = value1.transformToPinyin() let pinyin2 = value2.transformToPinyin() return pinyin1.compare(pinyin2) == (ascending ? .orderedAscending : .orderedDescending) } } return nil } }
|
["张三", "李四", "王五", "赵六", "钱七"].sortedByPinyin()
["张三", "李四", "王五", "赵六", "钱七"].sortedByPinyin(ascending: false)
[1, 2, 3, 4, 5, 6, 7].sortedByPinyin()
|