swift - 从原始值推断 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 枚举,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/

相关文章:

ios - iOS 中使用 parse.com 的帖子评分系统 - 赞成/反对

ios - 在 Swift 中创建应用程序文件夹时出错

swift - 使用 Swift 访问 JSON 数据

swift - 从作为闭包的实例属性访问 self

swift - OS X 中 iOS 的 UIImagePNGRepresentation() 的等效项是什么?

ios - 如何将用户默认的一个 TextView 中的数据保存到另一个 TextView 而不删除以前的数据?

swift - UIAlertController 快速管理系统声音

swift - 倒带时自动重新加载 TableViewController

ios - NavigationView 在纵向模式下消失

swift - Swift 构建中的类型检查规则?