create a tuple with the mapped name and surname of an array of user in swift

To create a tuple with the mapped name and surname of an array of user in Swift, you can use the map method on the array to transform each user object into a tuple containing their name and surname as separate properties.

main.swift
let users = [
    User(name: "John", surname: "Doe"),
    User(name: "Jane", surname: "Doe"),
    User(name: "Bob", surname: "Smith")
]

let nameSurnameTuples = users.map { ($0.name, $0.surname) }
197 chars
8 lines

In the above example, users is an array of User objects, each with a name and surname property. The map method transforms each User object into a tuple containing their name and surname, which we store in the nameSurnameTuples array.

The resulting nameSurnameTuples array will have the following contents:

main.swift
[("John", "Doe"), ("Jane", "Doe"), ("Bob", "Smith")]
53 chars
2 lines

Note that we're using shorthand syntax for the tuple creation with the ($0.name, $0.surname) syntax, which is equivalent to (name: $0.name, surname: $0.surname).

gistlibby LogSnag