須要擴展一個String類的方法swift
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.stringByReplacingOccurrencesOfString(" ", withString: "") } }