Swift ExpressibleByCustomTypeLiteral

Swift ExpressibleByCustomTypeLiteral,swift,swift-protocols,Swift,Swift Protocols,为什么没有这样的协议? 当然,只有当CustomType本身符合一些ExpressibleBySomeLiteral协议时,它才会进行许可 struct First: ExpressibleByDictionaryLiteral { let data: [String: Int] init(dictionaryLiteral elements: (String, Int)...) { data = .init(uniqueKeysWithValues:

为什么没有这样的协议?
当然,只有当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] 
[“一”:1,“二”:2,“三”:3]
不是
第一个
文本<代码>第一个文本不存在。语言的语法定义了一组固定的文字,您可以找到这些文字

[“一”:1,“二”:2,“三”:3]
是一个字典文本,因此
SimplifiedSecond
应该符合
ExpressibleByDictionaryTerral

struct SimplifiedSecond: ExpressibleByDictionaryLiteral {
    let first: First

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

嗯,我(和swift编译器)知道什么是字典文字,但不知道什么是“自定义类型文字”。“自定义类型文字”到底是什么?从您的用法来看,
SimplifiedSecond
也应该符合
ExpressibleByDictionaryLiteral
。初始化器应实现为
first=first(dictionaryLiteral:elements)
。你不同意吗?@Sweeper在示例“struct Second:ExpressibleByArrayLiteral”编译器中成功地处理了数组[CustomType],那么为什么它不能只管理CustomType内容呢?你意识到
[“一”:1,“二”:2,“三”:3]
不是
第一个
文本吗?这是一本字典。事实上,没有
First
文本。如果您想将任何类型的值从
First
隐式转换为
Second
,那么这违背了Swift的设计目标之一,即尽可能限制隐式类型转换。@Sweeper“在我看来,SimplifiedSecond也应该符合ExpressibleByDictionary Terral”您是对的。我认为这是一个解决办法。很简单,但不明显。你能不能把它贴出来作为答复,我会接受的。