ExpressibleByCustomTypeLiteral

ExpressibleByCustomTypeLiteral

为什么没有这样的协议?
当然只有当 CustomType 本身符合某些 ExpressibleBySomeLiteral 协议时才有意义。

struct First: ExpressibleByDictionaryLiteral {
    let data: [String: Int]
    
    init(dictionaryLiteral elements: (String, Int)...) {
        data = .init(uniqueKeysWithValues: elements)
    }
}

let f: First = ["one": 1, "two": 2, "three": 3]

struct Second: ExpressibleByArrayLiteral {
    let firsts: [First]
    
    init(arrayLiteral elements: First...) {
        firsts = elements
    }
}

let s: Second = [["one": 1, "two": 2, "three": 3],
                 ["four": 4, "five": 5],
                 ["six": 6, "seven": 7, "eight": 8, "nine": 9]]

以上所有代码都绝对有效,可以完美编译和运行。
但是当我们尝试以同样的方式做一些更简单的事情时,事实证明这是不可能的:

struct SimplifiedSecond: ExpressibleCustomTypeLiteral {
    let first: First

    init(customTypeLiteral element: First) {
        first = element
    }
}

let s: SimplifiedSecond = ["one": 1, "two": 2, "three": 3] 

您似乎想这样做:

let s: SimplifiedSecond = ["one": 1, "two": 2, "three": 3] 

["one": 1, "two": 2, "three": 3] 不是 First 字面意思 First 文字不存在。语言的语法定义了一组固定的文字,您可以找到 here.

["one": 1, "two": 2, "three": 3] 是一个字典字面量,所以 SimplifiedSecond 应该符合 ExpressibleByDictionaryLiteral 而不是:

struct SimplifiedSecond: ExpressibleByDictionaryLiteral {
    let first: First

    init(dictionaryLiteral elements: (String, Int)...) {
        first = First(dictionaryLiteral: elements)
    }
}