-1

I want to convert an array of users into a string of their names.

For example:

class User {
    var name: String

    init(name: String) {
        self.name = name
    }
}

let users = [
    User(name: "John Smith"),
    User(name: "Jane Doe"),
    User(name: "Joe Bloggs")
]
  1. Is this a good way to get the String: "John Smith, Jane Doe, Joe Bloggs"?

    let usersNames = users.map({ $0.name }).joinWithSeparator(", ")
    
  2. What if I want the last comma to be an ampersand? Is there a swift way to do that, or would I need to write my own method?

1

2 Answers 2

1

You can create a computed property. Try like this:

class User {
    let name: String
    required init(name: String) {
        self.name = name
    }
}

let users: [User] = [
    User(name: "John Smith"),
    User(name: "Jane Doe"),
    User(name: "Joe Bloggs")
]

extension _ArrayType where Generator.Element == User {
    var names: String {
        let people = map{ $0.name }
        if people.count > 2 { return people.dropLast().joinWithSeparator(", ") + " & " + people.last! }
        return people.count == 2 ? people.first! + " & " + people.last! : people.first ?? ""
    }
}

print(users.names) // "John Smith, Jane Doe & Joe Bloggs\n"
Sign up to request clarification or add additional context in comments.

Comments

-1
  1. You can use reduce:

    users.reduce("", combine: { ($0.isEmpty ? "" : $0 + ", ") + $1.name })
    
  2. Try this:

    func usersNames() -> String {
        var usersNames = users[0].name
        if users.count > 1 {
            for index in 1..<users.count {
                let separator = index < users.count-1 ? ", " : " & "
                usersNames += separator + users[index].name
            }
        }
        return usersNames
    }
    

2 Comments

Right, because it's answering the first question.
OK. That's OK. Thanks! :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.