-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?

ma11hew28
  • 121,420
  • 116
  • 450
  • 651

2 Answers2

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"
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
-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
    }
    
ma11hew28
  • 121,420
  • 116
  • 450
  • 651