ios - 如何使枚举可编码?

标签 ios swift xcode enums encode

这个问题在这里已经有了答案:





How do I make an enum Decodable in swift 4?

(9 个回答)


2年前关闭。




我有一个嵌套的 enumstruct 内我想符合Codable .如何制作枚举 codable因此使 struct可编码?

这是我所拥有的一个例子:

struct Person: Codable {
  var firstName: String
  var lastName: String 
  var favoriteColor: Color

  enum Color {
    case blue, red, green, yellow, pink, purple
  }
}

然后,我得到两个错误:

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

Type 'Person' does not conform to protocol 'Encodable'



我该如何解决这个问题?

编辑

我也尝试过使颜色符合 Codable。 Xcode 添加了这些协议(protocol) stub :
init(from decoder: Decoder) throws {
  <#code#>
}
func encode(to encoder: Encoder) throws {
  <#code#>
}

我该怎么办?

最佳答案

struct Person: Codable {
     var firstName: String
     var lastName: String
     var favoriteColor: Color
}

enum Color: String, Codable {
   case blue, red, green, yellow, pink, purple
}

关于ios - 如何使枚举可编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60957181/

相关文章:

ios - 应用程序在 iPhone x 中启动时崩溃?

ios - 分析与归档 - 不同的代码签名要求?

ios - 为什么我的 Tweak 不能正常工作?

ios - 每次框架初始化时 CoreData 都会被清除

ios - 如何在 iOS 后台从 Alamofire 获得稳定的连接

ios - 无法设置通过 loadView 创建的 UIScrollView 的 contentSize

ios - 检测单元格内 UILabel 上的点击

指向内存块中任意字节的 COpaquePointer

ios - View Controller 委托(delegate)返回 nil

xcode - XCTestCase 未在 setUp 类方法中启动应用程序