【问题标题】:swift - creating a String from an Object arrayswift - 从对象数组创建字符串
【发布时间】:2017-05-16 07:55:32
【问题描述】:

我有一个对象数组。

将其表示为 JSON 数组以便于理解对象数组

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

我需要创建一个字符串来连接数组中对象的属性之一。

输出:John, Doe

在不必遍历数组的情况下如何做到这一点的任何优雅方式?

【问题讨论】:

  • 你想如何格式化这个字符串?
  • 顺便说一句,您在代码 sn-p 中提到的数据类型应该是一个字典数组 ([[String: String]])。

标签: arrays swift string


【解决方案1】:

这里有一些选项

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

将产生 ["John", "Doe"]

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

将产生 JohnDoe

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

将产生 John,Doe

【讨论】:

  • 像魅力一样工作。谢谢
【解决方案2】:

没有循环的可能解决方案是 mapping 数组到 name 值和 joining 使用空格作为分隔符:

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

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

【讨论】:

    猜你喜欢
    • 2019-07-30
    • 1970-01-01
    • 2019-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-31
    • 2015-09-08
    相关资源
    最近更新 更多