从原始值推断Swift初始化程序

时间:2018-06-27 08:32:05

标签: 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枚举,this is the reason

1 个答案:

答案 0 :(得分:0)

我认为您需要遵守以下协议:

  • 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"
相关问题