gpt4 book ai didi

ios - 从 Swift Decodables 访问枚举的合适方法是什么?

转载 作者:搜寻专家 更新时间:2023-11-01 06:00:40 24 4
gpt4 key购买 nike

我有一个非常奇怪的案例,我使用 JSON 并认为我可以一直子字符串化到我想要访问的数据,但是,它没有按预期工作。

使用 QuickType,我能够转换这个 JSON:https://kidsuper.fodalabs.com/wp-json/wp/v2/art

到下面。

尝试访问时,似乎我应该能够执行 .acf.gallery.id 但是一旦我到达 acf.gallery,它会显示 .id 不存在。这很奇怪,但这是我尝试时返回的内容

let temp = imageArray[indexPath.row].acf.gallery.id
Value of type 'GalleryUnion?' has no member 'id'

只是为了好玩,我尝试了这个,但也没有运气:

let temp = imageArray[indexPath.row].acf.GalleryUnion.galleryElementArray
Error

: 'Acf' 类型的值没有成员 'GalleryUnion'

当我打印 .acf.gallery 时返回像这样开始:

Acf(company: "Season #3", 
gallery: Optional(weddingszn.GalleryUnion.galleryElementArray([weddingszn.GalleryElement(
id: 135, galleryID: 135, title: "1-791x1024",
filename: "1-791x1024.jpg", url: "https://kidsuper.fodalabs.com/wp-content/up

下面是我要解析的完整代码。有任何想法吗?

struct Acf: Codable {
let company: String
let gallery: GalleryUnion?
let tagline: String
let featuredImg: Bool?

enum CodingKeys: String, CodingKey {
case company, gallery, tagline
case featuredImg = "featured_img"
}
}

enum GalleryUnion: Codable {
case bool(Bool)
case galleryElementArray([GalleryElement])

init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let x = try? container.decode(Bool.self) {
self = .bool(x)
return
}
if let x = try? container.decode([GalleryElement].self) {
self = .galleryElementArray(x)
return
}
throw DecodingError.typeMismatch(GalleryUnion.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for GalleryUnion"))
}

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

struct GalleryElement: Codable {
let id, galleryID: Int
let title, filename: String
let url: String
let alt, author, description, caption: String
let name, date, modified: String
let mimeType: MIMEType
let type: TypeEnum
let icon: String
let width, height: Int
let sizes: Sizes

enum CodingKeys: String, CodingKey {
case id = "ID"
case galleryID = "id"
case title, filename, url, alt, author, description, caption, name, date, modified
case mimeType = "mime_type"
case type, icon, width, height, sizes
}
}

最佳答案

在向下钻取数组之前,您必须使用 if case、guard case 或 switch case 来解包枚举。

if case .galleryElementArray(let x) = imageArray[indexPath.row].acf.gallery {
print(x.first!.id)
}

关于ios - 从 Swift Decodables 访问枚举的合适方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52350279/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com