如何只从全名的姓氏中获取第一个字母?

时间:2018-05-07 14:25:31

标签: swift

我希望只获得姓氏的第一个字母以保护用户的隐私。示例:“John D.”

extension String
{
    public func getAcronyms(separator: String = "") -> String
    {
        let acronyms = self.components(separatedBy: " ").map({ String($0.characters.first!) }).joined(separator: separator);
        return acronyms;
    }
}

1 个答案:

答案 0 :(得分:4)

为了正确命名,您必须使用PersonNameComponentsFormatter.

let name =  "Joe Singh"
let nameFormatter = PersonNameComponentsFormatter()
if let nameComps  = nameFormatter.personNameComponents(from: name), let firstLetter = nameComps.givenName?.first, let lastName = nameComps.familyName {

     let sortName = "\(firstLetter). \(lastName)"  // J. Singh
 }

您还可以找到:

nameComps.middleName
nameComps.familyName
nameComps.nameSuffix 
nameComps.namePrefix   

还可以配置您的姓名格式

Default
short
long 
abbreviated