Sus*_*rma 4 enums struct swift decodable
我有这个枚举:
enum DealStatus:String {
case PENDING = "Pending"
case ACTIVE = "Active"
case STOP = "Stop"
case DECLINED = "Declined"
case PAUSED = "Paused"
}
Run Code Online (Sandbox Code Playgroud)
和结构:
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?
}
Run Code Online (Sandbox Code Playgroud)
在结构中我试图将枚举作为类型分配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?
}
Run Code Online (Sandbox Code Playgroud)
但我收到一些编译器错误:
类型'ActiveDeals'不符合协议'可解码'
协议需要初始化程序'init(from :)',类型为'Decodable'(Swift.Decodable)
无法自动合成'Decodable',因为'DealStatus'不符合'Decodable'
问题是Swift可以自动合成所需的方法,Decodable只有当结构的所有属性都是,Decodable而你的枚举不是Decodable.
刚刚在游乐场玩了一下,看起来你可以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"
}
Run Code Online (Sandbox Code Playgroud)