create a new array with the name and surname of a list of users in swift

To create a new array with the name and surname of a list of users in Swift, you can use a loop to iterate through the list of users and extract the name and surname data from each user data. Here's an example code:

main.swift
// sample user data
let users = [
    ["name": "John", "surname": "Doe"],
    ["name": "Jane", "surname": "Doe"],
    ["name": "Bob", "surname": "Smith"],
]

// create a new array with name and surname data
var nameAndSurnameArray = [String]()
for user in users {
    if let name = user["name"], let surname = user["surname"] {
        nameAndSurnameArray.append("\(name) \(surname)")
    }
}

// print the new array
print(nameAndSurnameArray)
444 chars
18 lines

In this code, the users variable contains an array of dictionaries that represent the user data. Each dictionary has name and surname keys that hold the corresponding data.

The nameAndSurnameArray variable is the new array that we want to create with the name and surname data. We initialize it to an empty array at first.

The loop iterates through each user data in the users array. We use optional binding (if let) to safely extract the name and surname data from each user data. Then, we append a new string to the nameAndSurnameArray variable that combines the name and surname data using string interpolation.

Finally, we print the nameAndSurnameArray variable to verify that it contains the correct data.

gistlibby LogSnag