简体   繁体   中英

swift - creating a String from an Object array

I have an array of objects.

representing it as a JSON array to easily understand the object array

[
  {
    id:343,
    name:"John"
  },
  {
    id:342,
    name:"Doe"
  }
]

I need to create a String concatenating one of the properties of the objects in array.

Output: John, Doe

Any elegant way of how to do it without having to loop through the array?

A possible solution without loop is map ping the array to the name values and join ing them using a space as separator:

let array = [["id":343, "name":"John"], ["id":342, "name":"Doe"]]

let fullName = array.map{$0["name"] as! String}.joined(separator: " ")

Here are a number of options

a.map({$0.name}).description

will produce ["John", "Doe"]

a.map({$0.name}).joined()

will produce JohnDoe

a.map({$0.name}).joined(separator:",")

will produce John,Doe

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