如何通过各种变体参数 如何仅传递可变参数:

问题描述

struct Data: ExpressibleByDictionaryLiteral {
    let storage: keyvaluePairs<String,Int>
    
    init(dictionaryLiteral elements: (String,Int)...) {
        storage = keyvaluePairs(dictionaryLiteral: elements)
    }
}

编译错误

不能将类型[[(String,Int)]'的数组传递为的可变参数 输入'((String,Int)'

我知道这全都与“ splatting”有关,而尚不存在该语言(顺便问一下,什么时候会出现?),这里有很多变通办法来初始化该结构。
但这太奇怪了。我正以所需的keyvaluePairs初始值设定项形式获取元素,我不能直接将其传递出去!

解决方法

如何仅传递可变参数:

像这样:

Data(dictionaryLiteral: ("key",1))
// or 
Data(dictionaryLiteral: ("key1",1),("key2",2))

如您所见,您可以传递任意数量的变量作为第一个参数。

但是

好像您正在尝试将array传递给初始值设定项,如果是这样,您应该为此设置一个初始值设定项:

init(dictionaryLiteral elements: [(String,Int)]) {
    storage = KeyValuePairs(dictionaryLiteral: elements)
}

然后您也可以传递数组:

Data(dictionaryLiteral: [("key1",2)])

如何使其编译?

(并按预期工作)

由于Swift尚不支持 Splatting ,并且您正在尝试实现Dictionary,因此应重新考虑struct的结构。因此存储应为Dictionary

let storage: [String: Int]

然后,您可以实现上面讨论的第二个初始化程序,然后在所需的初始化程序中使用它,例如:

struct Data: ExpressibleByDictionaryLiteral {
    let storage: [String: Int]

    init(dictionaryLiteral elements: (String,Int)...) {
        self.init(dictionary: elements.reduce(into: [Key: Value](),{ (result,tuple) in
            result[tuple.0] = tuple.1
        }))
    }

    init(dictionary: [Key: Value]) {
        storage = dictionary
    }
}