添加字典斯威夫特数组 [英] Add a dictionary to an array in Swift

查看:152
本文介绍了添加字典斯威夫特数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了字典的数组,但我有一个错误,当我试图在我的对象(字典)添加到我的数组。
我有这样的错误AnyObject没有一个名为'追加'成员

I created an array of dictionary, but I have an error, when I tried to add my object (a dictionary) to my array. I have this error "AnyObject does not have a member named 'append'"

var posts=[Dictionary<String,AnyObject>]()

var post=Dictionary<String,AnyObject>()
var attachment=Dictionary<String,AnyObject>()

...

post=["id":"a", "label":"b"]
attachment=["id":"c", "image":"d"]
var newPost = [post, attachment]

posts.append(newPost) <- AnyObject does not have a member named 'append'

我不明白。也许我没有正确初始化数组?

I don't understand. Maybe I haven't initialize the array correctly ?

更新 / 解决

var posts=[Dictionary<String,Dictionary<String,AnyObject>>]()

var post=Dictionary<String,AnyObject>()
var attachment=Dictionary<String,AnyObject>()

...

post=["id":"a", "label":"b"]
attachment=["id":"c", "image":"d"]
var newPost = ["post":post, "attachment":attachment]

posts.append(newPost) <- AnyObject does not have a member named 'append'

编辑:newPost是字典的一个实例,并张贴字典的数组

EDIT : newPost is a instance of dictionary and posts an array of dictionaries

推荐答案

追加是增加一个项目,而你试图追加另一个数组(是字典的数组)。您可以使用 + = 运营商:

append is to add an item, whereas you are trying to append another array (post is an array of dictionaries). You can use the += operator:

posts += newPost

延长方法(等同于 + = 运算符):

or use the extend method (which is equivalent to the += operator):

posts.extend(newPost)

或单独添加元素:

posts.append(post)
posts.append(attachment)

这篇关于添加字典斯威夫特数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆