作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我有这个枚举:
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/
我是一名优秀的程序员,十分优秀!