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!

Sentry mobile image

Tired of users complaining about slow app loading and janky UI?

Improve performance with key strategies like TTID/TTFD & app start analysis.

Read the blog post

Top comments (0)

Sentry mobile image

App store rankings love fast apps - mobile vitals can help you get there

Slow startup times, UI hangs, and frozen frames frustrate users—but they’re also fixable. Mobile Vitals help you measure and understand these performance issues so you can optimize your app’s speed and responsiveness. Learn how to use them to reduce friction and improve user experience.

Read full post →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay