【问题标题】:Swift 4 Get data from structureSwift 4 从结构中获取数据
【发布时间】:2018-07-17 17:59:37
【问题描述】:

我有结构(下面的代码),我把 JSON 值放在那里。如何从我的结构中获取 name: cafe 的 image:URL?

例如:

  • 名称:“咖啡馆”图片:“url_link”
  • 名称:“bar”图片:“url_link”
  • 名称:“sushi”图片:“url_link”

我的结构

struct Root: Codable {
    let  data: [InnerItem]
}
struct InnerItem:Codable {
    let  id: Int?
    let  image: String?
    let  name: String?

    private enum CodingKeys : String, CodingKey {
        case id = "id", image = "image", name = "name"
    }
}

【问题讨论】:

  • 仅供参考 - 如果键都与您的属性名称匹配,则无需定义 CodingKeys。
  • ... 并且——正如您在 previous question 中已经提到的——将结构成员声明为非可选的(没有问号)。

标签: swift structure extract


【解决方案1】:

你可以试试

do {
      let decoder = try JSONDecoder().decode(Root.self, from: response.data!)
      let innerCafe = decoder.data.first(where: { $0.name == "cafe" })   
  }
  catch {
      print(error)
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-02
    • 2019-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多