我是 Swift 新手,正在为我的项目研究功能标志概念,但我一直坚持使用可编码作为默认标志值。目前我的代码看起来像这样
import Foundation
class KillSwitches: Codable {
public enum CodingKeys: String, CodingKeys {
case featureOne
case featureTwo
case featureThree
}
let featureOne: Bool = true
let featureTwo: Bool = true
let featureThree: Bool = false
}
我有内部帮助器类,有助于对 json 文件中的所有值进行编码和解码,这就是为什么这里没有明确提及它的原因。在此实现之前,我没有任何默认值,并且使用结构从远程配置文件中读取所有内容,该文件工作正常。现在,如果远程配置文件无法访问,我将在下一步中为我的功能设置默认值。
我期望我可以初始化这个类,这样我就会得到一个默认的类对象,就像我从远程文件读取时得到的一样。
如果不传递 init(来自解码器:),我无法实例化此类。我什至尝试过做
KillSwitches.init(from: KillSwitches.self)
这也不起作用,我得到的类型不符合预期的类型解码器。
我的 Json 看起来像这样
{
"featureOne" : false,
"featureTwo" : true,
"featureThree" : true
}
非常感谢任何解决此问题的指导/指示。
一旦您遵循
Encodable
,就好像您的类已经显式声明了 encode(to:)
方法和 init(from:)
初始化程序。
通过声明带参数的初始化程序,当所有属性都有默认值时,您会立即丢失编译器为您生成的默认(无参数)初始化程序。这就是为什么你不能这样做
KillSwitches()
。这在文档中有说明:
Swift 为任何结构或类提供了默认的初始化器 为其所有属性提供默认值 并且不提供 至少有一个初始值设定项本身。 默认初始值设定项只是 创建一个新实例,并将其所有属性设置为默认值 价值观。
KillSwitches
已经有 init(from:)
初始化程序,因此 Swift 不提供默认初始化程序。
您只需自己添加无参数初始化程序即可:
class KillSwitches: Codable {
public enum CodingKeys: String, CodingKey {
case featureOne
case featureTwo
case featureThree
}
let featureOne: Bool = true
let featureTwo: Bool = true
let featureThree: Bool = false
init() { }
}
然后你可以做:
let defaultKillSwitches = KillSwitches()
如果您想要默认值。
如果您使用 extension 为类定义它的 Codable
,则可以保存使用默认初始值设定项的能力class KillSwitches {
let featureOne: Bool = true
let featureTwo: Bool = true
let featureThree: Bool = false
}
extension KillSwitches: Codable {
public enum CodingKeys: String, CodingKeys {
case featureOne, featureTwo, featureThree
}
}