swift - 在没有数据的情况下初始化 DictionaryLiteral

标签 swift dictionary

我想初始化一个没有任何数据的 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/

相关文章:

ios - MapBox:如何删除一个形状并绘制另一个形状?

swift - 删除时为表格 View 单元格设置动画

ios - 如何使用 SNI 获取自定义 NSURLProtocol

ios - DateComponents 似乎不尊重年份

dictionary - Elixir 中的 HashDict 和 OTP GenServer 上下文

dictionary - 定义一个空的 Dict,其中值是抽象类型的子类型

ios - 在 iPhone 5S 上隐藏 UIImage

ios - 使用 Parse 框架的 Xcode 6 Playground ?

iphone - 使用 Plist 字典进行应用程序设置

要听写的元组的 Python 列表