swift - Swift 4 支持 swagger 代码生成
问题描述
我面临从 YAML 文件生成 swift 模型的问题。
swagger-codegen generate -i swagger_1.yaml -l swift4
下面是示例模型之一。这不是在 swift 4 中构建的。因为没有编码密钥
import Foundation
open class User: Codable {
public enum Sex: String, Codable {
case male = "male"
case female = "female"
}
public var id: Int64?
public var username: String?
public var firstName: String?
public var lastName: String?
public var sex: Sex?
public init(id: Int64?, username: String?, firstName: String?, lastName: String?, sex: Sex?) {
self.id = id
self.username = username
self.firstName = firstName
self.lastName = lastName
self.sex = sex
}
// Encodable protocol methods
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: String.self)
try container.encodeIfPresent(id, forKey: "id")
try container.encodeIfPresent(username, forKey: "username")
try container.encodeIfPresent(firstName, forKey: "firstName")
try container.encodeIfPresent(lastName, forKey: "lastName")
try container.encodeIfPresent(sex, forKey: "sex")
}
// Decodable protocol methods
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: String.self)
id = try container.decodeIfPresent(Int64.self, forKey: "id")
username = try container.decodeIfPresent(String.self, forKey: "username")
firstName = try container.decodeIfPresent(String.self, forKey: "firstName")
lastName = try container.decodeIfPresent(String.self, forKey: "lastName")
sex = try container.decodeIfPresent(Sex.self, forKey: "sex")
}
}
也在 GitHub 上发布了这个问题。
解决方案
您需要添加enum CodingKeys
和重写 initFromDecoder/encode。
同样在您的情况下,根本不需要单独的编码/解码/编码键,因为类的所有属性都已经是可编码的。
open class User: Codable {
....
enum CodingKeys: String, CodingKey {
case id, username, firstName, lastName, sex
}
// Encodable protocol methods
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encodeIfPresent(id, forKey: .id)
try container.encodeIfPresent(username, forKey: .username)
try container.encodeIfPresent(firstName, forKey: .firstName)
try container.encodeIfPresent(lastName, forKey: .lastName)
try container.encodeIfPresent(sex, forKey: .sex)
}
// Decodable protocol methods
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decodeIfPresent(Int64.self, forKey: .id)
username = try container.decodeIfPresent(String.self, forKey: .username)
firstName = try container.decodeIfPresent(String.self, forKey: .firstName)
lastName = try container.decodeIfPresent(String.self, forKey: .lastName)
sex = try container.decodeIfPresent(Sex.self, forKey: .sex)
}
}
推荐阅读
- mysql - 如何一次编辑时间戳列中的所有值?
- c++11 - 为什么 auto 变量的输出显示与类型无关的内容?
- pega - 属性集不是设置值
- java - 使用ntp获取网络时间服务器
- c++ - 有效计算像素与其对应的极线的距离
- .net - Azure Pipelines yml 帮助 - 了解我的 yml 文件及其未部署的原因
- php - 在 PHP 中接受 cookie 同意后防止页面刷新
- javascript - get key:value pair inside sub-blocks
- f# - 清除 F# 中的所有事件处理程序?
- autohotkey - AutoHotKey 脚本的内容感知