swift - 从原始值推断 Swift 初始化器
问题描述
我有以下 Swift 枚举,可确保仅使用纯 json 类型。
public enum JSONValue {
case string(String)
case integer(Int)
case double(Double)
case bool(Bool)
public init(_ value: String) {
self = .string(value)
}
public init(_ value: Int) {
self = .integer(value)
}
public init(_ value: Double) {
self = .double(value)
}
public init(_ value: Bool) {
self = .bool(value)
}
}
要初始化 JSON 值,必须这样做
let json = JSONValue.string("my value")
或者在字典的情况下
let params: [String: JSONValue] = [
"my string": JSONValue.string("my value"),
"my int": JSONValue.init(10)
]
有没有办法从原始值推断初始化程序以方便这样的使用:
let json: JSONValue = "my value"
let params: [String: JSONValue] = [
"my string": "my value",
"my int": 10
]
(题外话,但如果你想知道为什么我需要这个 JSONValue 枚举,这就是原因
解决方案
我认为您需要遵守以下协议:
ExpressibleByBooleanLiteral
ExpressibleByIntegerLiteral
ExpressibleByFloatLiteral
ExpressibleByStringLiteral
像这样
public enum JSONValue: ExpressibleByBooleanLiteral, ExpressibleByIntegerLiteral, ExpressibleByFloatLiteral, ExpressibleByStringLiteral {
public typealias BooleanLiteralType = Bool
public typealias IntegerLiteralType = Int
public typealias FloatLiteralType = Double
public typealias StringLiteralType = String
case string(String)
case integer(Int)
case double(Double)
case bool(Bool)
public init(stringLiteral value: String) {
self = .string(value)
}
public init(integerLiteral value: Int) {
self = .integer(value)
}
public init(floatLiteral value: Double) {
self = .double(value)
}
public init(booleanLiteral value: Bool) {
self = .bool(value)
}
}
这将允许编译器执行一些魔术:
let jsonValue: JSONValue = "Hello World"
推荐阅读
- amazon-web-services - 创建请求正文和模板 API GATEWAY CDK
- java - 如何通过其 ID 持久化具有多对一字段的新 JSON 对象?
- istio - Istio 使用企业代理背后的 TLS 发起访问外部站点
- python - 我的 A-star 实施似乎很慢,需要关于我做错了什么的建议和帮助
- database - 您可以通过 inno 设置从数据库中获取数据吗?
- python - 检索 Kivy 中复选框的值
- python-3.x - 使用 np.where() 检查 pd.DataFrame 的条件并将函数应用于多个列
- sql - 在 SQL Server 中使用 GroupBy() 而不是分组记录计数时如何获取表中所有行的计数
- python - 是否可以在 Kwargs 中注入 python 代码以及如何防止此用户输入
- mysql - mysql 在使用 join 查询后触发