簡體   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