繁体   English   中英

Swift:将对象数组转换为字符串?

[英]Swift: Convert an array of objects into a string?

我想将一组用户转换为他们姓名的字符串。

例如:

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. 这是获取String的好方法: "John Smith, Jane Doe, Joe Bloggs"吗?

     let usersNames = users.map({ $0.name }).joinWithSeparator(", ")
  2. 如果我希望最后一个逗号是 & 号怎么办? 有没有一种快速的方法可以做到这一点,还是我需要编写自己的方法?

您可以创建计算属性。 像这样尝试:

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. 您可以使用reduce

     users.reduce("", combine: { ($0.isEmpty ? "" : $0 + ", ") + $1.name })
  2. 尝试这个:

     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 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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