Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
143 views
Welcome To Ask or Share your Answers For Others

1 Answer

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
"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...