gpt4 book ai didi

swift - 可解码符合枚举类型的属性

转载 作者:搜寻专家 更新时间:2023-10-31 21:52:07 26 4
gpt4 key购买 nike

我有这个枚举:

enum DealStatus:String {
case PENDING = "Pending"
case ACTIVE = "Active"
case STOP = "Stop"
case DECLINED = "Declined"
case PAUSED = "Paused"
}

和结构:

struct ActiveDeals: Decodable {
let keyword: String
let bookingType: String
let expiryDate: Int
let createdAt: Int?
let shopLocation: String?
let dealImages: [DealImages]?
let dealStatus: String?
let startingDate: Int?
}

在结构中,我试图将枚举分配为 dealStatus 的类型,如下所示:

struct ActiveDeals: Decodable {
let keyword: String
let bookingType: String
let expiryDate: Int
let createdAt: Int?
let shopLocation: String?
let dealImages: [DealImages]?
let dealStatus: DealStatus
let startingDate: Int?
}

但是我遇到了一些编译器错误:

Type 'ActiveDeals' does not conform to protocol 'Decodable'

Protocol requires initializer 'init(from:)' with type 'Decodable'(Swift.Decodable)

Cannot automatically synthesize 'Decodable'because 'DealStatus' does not conform to 'Decodable'

最佳答案

问题是 Swift 可以自动合成 Decodable 所需的方法,只有当一个结构的所有属性也是 Decodable 而你的枚举不是 Decodable

刚刚在 playground 上试了一下,似乎你可以让你的枚举 Decodable 只需声明它是,Swift 会自动为你合成这些方法。即

enum DealStatus:String, Decodable  
// ^^^^^^^^^ This is all you need
{
case PENDING = "Pending"
case ACTIVE = "Active"
case STOP = "Stop"
case DECLINED = "Declined"
case PAUSED = "Paused"
}

关于swift - 可解码符合枚举类型的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48783631/

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