macOS我的收藏

swift 之玩转中文首字母排序

2017-01-05  本文已影响955人  风飞燕
大爱龙马.jpg
正式开始,简单的理解就是砸门手机的通讯录(≧▽≦)/啦啦啦,偶们存在通讯录中的小伙伴的爱称是不是就是从A~Z排序的啦,不废话了,直接上代码
import UIKit
//提示:那个模型自己去建哈,很简单的
class ViewController: UIViewController {

    var nameArray = ["马自达","本田","路虎","大众","奔驰","奥迪","丰田","斯柯达","jeep"]
    var charArr : [String] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
      var addressBookDict = [String:[PPPersonModel]]()

        for i in 0..<nameArray.count {
            
            let   model  : PPPersonModel   = PPPersonModel ()
            
            model.name = nameArray[i]
            // 获取到姓名的大写首字母
            let firstLetterString = getFirstLetterFromString(aString: model.name)
            
            if addressBookDict[firstLetterString] != nil {
                // swift的字典,如果对应的key在字典中没有,则会新增
                addressBookDict[firstLetterString]?.append(model)
                
            } else {
                let arrGroupNames = [model]
                addressBookDict[firstLetterString] = arrGroupNames
            }

                   }
        
        
        var nameKeys = Array(addressBookDict.keys).sorted()
        
        // 将 "#" 排列在 A~Z 的后面
        if nameKeys.first == "#" {
            nameKeys.insert(nameKeys.first!, at: nameKeys.count)
            nameKeys.remove(at: 0);
        
      //            self.charArr.addEntriesFromDictionary(
        }
        
        print("\(nameKeys) ")
        print(addressBookDict.values)
        
        for i in 0..<nameKeys.count {
            let key = nameKeys[i]
            
            let  modelArr = addressBookDict[key]
//             print(modelArr?.count)
           // Expected '{' to start the body of for-each loop
            let  count = modelArr!.count
            for j in 0..<count {
                let  model:PPPersonModel = modelArr![j]
                   charArr.append(model.name)
            }
        }
         print(charArr)

    }
    // MARK: - 获取联系人姓名首字母(传入汉字字符串, 返回大写拼音首字母)
      func getFirstLetterFromString(aString: String) -> (String) {
        
        // 注意,这里一定要转换成可变字符串
        let mutableString = NSMutableString.init(string: aString)
        // 将中文转换成带声调的拼音
        CFStringTransform(mutableString as CFMutableString, nil, kCFStringTransformToLatin, false)
        // 去掉声调(用此方法大大提高遍历的速度)
        let pinyinString = mutableString.folding(options: String.CompareOptions.diacriticInsensitive, locale: NSLocale.current)
        // 将拼音首字母装换成大写
        let strPinYin = polyphoneStringHandle(nameString: aString, pinyinString: pinyinString).uppercased()
        // 截取大写首字母
        let firstString = strPinYin.substring(to: strPinYin.index(strPinYin.startIndex, offsetBy:1))
        // 判断姓名首位是否为大写字母
        let regexA = "^[A-Z]$"
        let predA = NSPredicate.init(format: "SELF MATCHES %@", regexA)
        return predA.evaluate(with: firstString) ? firstString : "#"
    }
    
    
    /// 多音字处理
    func polyphoneStringHandle(nameString:String, pinyinString:String) -> String {
        if nameString.hasPrefix("长") {return "chang"}
        if nameString.hasPrefix("沈") {return "shen"}
        if nameString.hasPrefix("厦") {return "xia"}
        if nameString.hasPrefix("地") {return "di"}
        if nameString.hasPrefix("重") {return "chong"}
        
        return pinyinString;
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

这里是打印的结果

45CB9524-47A0-439D-B122-F91AF25F1EFD.png

啦啦啦,搞定了,能力有限,有些地方做的不好希望大家提提意见,话说就这么一个小小的功能差不多100行代码,感觉有丢丢多,真心的。

上一篇 下一篇

猜你喜欢

热点阅读