我有以下 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 枚举,this is the reason
最佳答案
我认为你需要遵守以下协议(protocol):
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"
关于swift - 从原始值推断 Swift 初始化器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51058121/