【问题标题】:Swift: Convert an array of objects into a string?Swift:将对象数组转换为字符串?
【发布时间】:2016-04-07 22:21:46
【问题描述】:

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

例如:

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. 如果我希望最后一个逗号是 & 号怎么办?有没有一种快速的方法可以做到这一点,还是我需要编写自己的方法?

【问题讨论】:

标签: arrays string swift


【解决方案1】:

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

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"

【讨论】:

    【解决方案2】:
    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
      }
      

    【讨论】:

    • 对,因为它回答了第一个问题。
    • 好的。没关系。谢谢! :-)
    猜你喜欢
    • 2017-08-24
    • 2021-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-09
    • 1970-01-01
    相关资源
    最近更新 更多