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!

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

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

Okay