我想初始化一个没有任何数据的 Swift DictionaryLiteral 对象。
如:
var withoutData: DictionaryLiteral = [String: [RealmObject]]()
但是,这会产生错误 Cannot convert value of type '[String : [RealmObject]]' to specified type 'DictionaryLiteral'
但如果我直接对数据做同样的事情,它会起作用:
var withData: DictionaryLiteral = ["test": [RealmObject()]]
背后的原因是什么? 以及如何声明一个空变量 DictionaryLiteral?
最佳答案
在您的第一个示例中,您正在创建一个 Dictionary
然后尝试初始化 DictionaryLiteral
用它。它们是两种不同的类型,因此是错误的。您可以使用 ()
创建DictionaryLiteral
, 但您必须正确指定您正在创建的类型。 DictionaryLiteral
使用 String
作为键和 [RealmObject]
因为该值由 DictionaryLiteral<String, [RealmObject]>
指定.
在您的第二个示例中,您提供了一个实际的字典文字,因此 Swift 能够将类型推断为 DictionaryLiteral<String, [RealmObject]>
。 .没有 Dictionary
实际上曾经被创造过。
创建空 DictionaryLiteral
的一种方法就是在创建的时候完全指定类型,让Swift推断变量类型:
var withoutData = DictionaryLiteral<String, [RealmObject]>()
另一种方法是完全指定变量的数据类型,然后用空字典字面量初始化变量 [:]
作为JonJ shows in his answer .
关于swift - 在没有数据的情况下初始化 DictionaryLiteral,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53170622/