gpt4 book ai didi

swift - 什么是 Typescript 联合类型的 Swift 等价物?

转载 作者:行者123 更新时间:2023-12-05 08:30:10 25 4
gpt4 key购买 nike

我想在 Swift 上创建这样的东西它是为了 Alamofire json 解析

interface Question {
value: string;
data: [string]
}

interface Advice {
type: string;
data: { value: string }
}

interface CurrentItem {
type: string;
data: Advice | Question | string
}

最佳答案

使用具有关联值的枚举来表示不同的可能性:

enum Data {
case advice (Advice)
case question (Question)
case string (String)
}

然后您可以将 CurrentItem 创建为结构

struct CurrentItem {
type: String
data: Data
}

如果您从 JSON 解码,您需要使结构符合 Decodable 并编写自定义 init(from decoder: Decoder) 方法来查看提供的数据,然后创建适当的数据枚举的实例。

关于swift - 什么是 Typescript 联合类型的 Swift 等价物?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65779401/

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