【问题标题】:Access value from model从模型中访问值
【发布时间】:2023-02-21 11:39:53
【问题描述】:

有人可以告诉我如何访问这个值:struct ImgSrcSetClass 内的 var the15X: String 吗?

这是模型:

import Foundation

struct Fish: Codable, Identifiable {
    var id: Int
    var name: String
    var url: String
    var imgSrcSet: ImgSrcSetUnion
    var meta: Meta

    enum CodingKeys: String, CodingKey {
        case id, name, url
        case imgSrcSet = "img_src_set"
        case meta
    }
}

enum ImgSrcSetUnion: Codable {
    case enumeration(ImgSrcSetEnum)
    case imgSrcSetClass(ImgSrcSetClass)

    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        if let x = try? container.decode(ImgSrcSetEnum.self) {
            self = .enumeration(x)
            return
        }
        if let x = try? container.decode(ImgSrcSetClass.self) {
            self = .imgSrcSetClass(x)
            return
        }
        throw DecodingError.typeMismatch(ImgSrcSetUnion.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for ImgSrcSetUnion"))
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        switch self {
        case .enumeration(let x):
            try container.encode(x)
        case .imgSrcSetClass(let x):
            try container.encode(x)
        }
    }
}

// MARK: - ImgSrcSetClass
struct ImgSrcSetClass: Codable {
    var the15X: String
    var the2X: String?

    enum CodingKeys: String, CodingKey {
        case the15X = "1.5x"
        case the2X = "2x"
    }
}

enum ImgSrcSetEnum: String, Codable {
    case notAvailable = "Not available"
}

例如,我可以通过调用 Text(fish.name) 来获取名称。 但我不知道如何访问 img-URL。

此外,这是我正在获取的 json 模式:

{
    "id": 1097,
    "name": "Waspfish",
    "url": "https://en.wikipedia.org/wiki/Waspfish",
    "img_src_set": {
      "1.5x": "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b5/YamahimeK.jpg/330px-YamahimeK.jpg",
      "2x": "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b5/YamahimeK.jpg/440px-YamahimeK.jpg"
    },
    "meta": {
      "scientific_classification": {
        "kingdom": "animalia",
        "phylum": "chordata",
        "class": "actinopterygii",
        "order": "scorpaeniformes",
        "family": "scorpaenidae",
        "subfamily": "tetraroginaej._l._b._smith,_1949"
      }
    }
  }

【问题讨论】:

    标签: json swift rest swiftui


    【解决方案1】:

    您似乎在名为fish 的变量中有一个Fish 的实例。

    let fish: Fish = ...
    

    您可以通过以下方式查看imgSrcSet

    if case let .imgSrcSetClass(imgSrcSet) = fish.imgSrcSet {
        let the15x = imgSrcSet.the15X
        print(the15x)
    }
    

    如果fish.imgSrcSet的值是枚举大小写.imgSrcSetClassif的内容将被执行。变量imgSrcSet 将被设置为案例的关联值。这使您可以访问 ImgSrcSetClass 值的属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-25
      • 2023-01-03
      • 1970-01-01
      • 2011-03-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多