Freelancing for Pale Blue

Looking for flexible work opportunities that fit your schedule?


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

iOS Apr 12, 2024

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)"
    }
}

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

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

Happy coding!

Tags

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.