DEV Community

RockAndNull
RockAndNull

Posted on • Originally published at paleblueapps.com on

How to format the name and surname of a person in Swift

How to format the name and surname of a person in Swift

I mean, how hard it can be? Isn't it something like that?

struct Person {
    var name: String
    var surname: String

    var fullname: String {
        "\(name) \(surname)"
    }
}
Enter fullscreen mode Exit fullscreen mode

But that's not always the case.

Here at Pale Blue, we collaborate with individuals worldwide, and one thing I learned is that there are countries where the last name comes before the first name. But how can we make sure that our app will respect the order of the names based on locale?

This is where the PersonNameComponentsFormatter comes in.

import Foundation

struct Person {
    var name: String
    var surname: String

    var fullname: String {
        var components = PersonNameComponents()
        components.givenName = name
        components.familyName = surname

        return formatter.string(from: components)
    }
}

/// This is out of the computed property just to simplify the change of locale for demo purposes
let formatter = PersonNameComponentsFormatter()

var person = Person(name: "Michael", surname: "Mavris")
print(person.fullname) // Michael Mavris

formatter.locale = Locale(identifier: "vi_VN")
print(person.fullname) // Mavris Michael

Enter fullscreen mode Exit fullscreen mode

Now, our fullname property adapts to the user's locale, displaying names in the expected order.

Happy coding!

Top comments (0)