Tom B.
Tom B.

Reputation: 124

How to get only first letter from last name of full name?

I want to get only first letter from last name for privacy of users. Example: "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;
    }
}

Upvotes: 3

Views: 2389

Answers (1)

Jogendar Choudhary
Jogendar Choudhary

Reputation: 3494

For proper naming, you have to use 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
 }

You can also find:

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

And also can configured the format of your names

Default
short
long 
abbreviated

Upvotes: 10

Related Questions