代码之家  ›  专栏  ›  技术社区  ›  Jan

从原始值推断swift初始化器

  •  1
  • Jan  · 技术社区  · 6 年前

    下面的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 回复  |  直到 6 年前
        1
  •  0
  •   Sweeper    6 年前

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

    • 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"