How to use PersonNameComponents Formatter


Greetings, traveler!

There are a lot of apps where a user name is displayed. To display a person’s name, we can do something like this:

struct User {
    let givenName: String
    let familyName: String
}

let user = User(givenName: "Artem", familyName: "Mirzabekian")
let labelText = "\(user.givenName) \(user.familyName)" // Artem Mirzabekian

If your user is from the Western Hemisphere, this code is likely not a problem for them. However, in some other countries, names are written in a different.

PersonNameComponents Formatter

There is an automatic way to handle this situation. You can use a convenient Apple API called PersonNameComponentsFormatter. Check out this example:

extension User {
    var fullName: String {
        let personNameFormatter = PersonNameComponentsFormatter()
        personNameFormatter.locale = Locale.current
        
        var components = PersonNameComponents()
        components.givenName = givenName
        components.familyName = familyName
        
        return personNameFormatter.string(from: components)
    }
}

user.fullName // Artem Mirzabekian

You can change the Locale and recheck the result. Let’s use the Japanese Locale, for example. As you can see, the result is different.

extension User {
    var fullName: String {
        let personNameFormatter = PersonNameComponentsFormatter()
        personNameFormatter.locale = Locale(identifier: "ja_JP")
        
        var components = PersonNameComponents()
        components.givenName = givenName
        components.familyName = familyName
        
        return personNameFormatter.string(from: components)
    }
}

user.fullName // Mirzabekian Artem

Conclusion

The user may not always notice your efforts, but sometimes being invisible to them can mean high quality and attention to detail.