附加到[String:Any]字典结构中的数组

编程入门 行业动态 更新时间:2024-10-19 15:34:03
本文介绍了附加到[String:Any]字典结构中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

组装传递给 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]字典结构中的数组

本文发布于:2023-11-26 20:52:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1635150.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   字典   结构   String

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!