附加到[String:Any]字典结构中的数组 [英] Append to array in [String: Any] dictionary structure
问题描述
组装传递给 GRMustache.swift> a的数据有效载荷以渲染胡须模板,我处于一种需要的场景中将数据附加到先前在字典中定义的数组.
Assembling a data payload passed to GRMustache.swift for rendering mustache templates, I'm in a scenario where I need to append data to an array previously defined in the dictionary.
我的数据结构开始于:
var data: [String: Any] = [
"key1": "example value 1",
"key2": "example value 2",
"items": [
// I need to append here later
]
]
items
键对是我以后需要在循环中附加的集合.
The items
key pair is a collection I need to append later within a loop.
要添加到data["items"]
数组中,我正在尝试类似的操作:
To add to the data["items"]
array, I'm trying something like:
for index in 1...3 {
let item: [String: Any] = [
"key": "new value"
]
data["items"].append(item)
}
此错误,因为类型Any?
的值没有成员append
,并且二进制运算符+=
无法应用于类型Any?
和[String : Any]
的操作数.
This errors, as value of type Any?
has no member append
, and binary operator +=
cannot be applied to operands of type Any?
and [String : Any]
.
这很有意义,因为我需要强制转换要附加的值;但是,我无法更改数组.
This makes sense, as I need to cast the value to append; however, I can't mutate the array.
投射到数组,是否强制向下转换会产生错误:
Casting to array, whether forcing downcast gives the error:
(data["items"] as! Array).append(item)
有吗?"不能转换为'Array< _>';您是要使用"as!"吗?强迫低垂?
'Any?' is not convertible to 'Array<_>'; did you mean to use 'as!' to force downcast?
不能在'Array< _>'类型的不可变值上使用变异成员
Cannot use mutating member on immutable value of type 'Array<_>'
似乎我的演员选错了;或者,也许我会以错误的方式来解决这个问题.
Seems like my cast is wrong; or, perhaps I'm going about this in the wrong way.
关于如何随着时间的推移逐步填充data["items"]
的任何建议?
Any recommendation on how to fill data["items"]
iteratively over time?
推荐答案
data[Items]
的类型不是Array
,实际上是Array<[String: Any]>
.
The type of data[Items]
isn't Array
but actually Array<[String: Any]>
.
您可以将其压缩为更少的步骤,但是我更喜欢多步操作的清晰性:
You could probably squeeze this into fewer steps, but I prefer the clarity of multiple steps:
var data: [String: Any] = [
"key1": "example value 1",
"key2": "example value 2",
"items": []
]
for index in 1...3 {
let item: [String: Any] = [
"key": "new value"
]
// get existing items, or create new array if doesn't exist
var existingItems = data["items"] as? [[String: Any]] ?? [[String: Any]]()
// append the item
existingItems.append(item)
// replace back into `data`
data["items"] = existingItems
}
这篇关于附加到[String:Any]字典结构中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!