简体   繁体   中英

Swift: Convert an array of objects into a string?

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?

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"
  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 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM