在Swift中向数组添加字典

时间:2014-11-12 21:43:32

标签: arrays dictionary swift

我创建了一个字典数组,但是当我尝试将我的对象(字典)添加到我的数组时,我有一个错误。 我有这个错误" AnyObject没有名为'追加'"

的成员
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'

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

更新 / 已解决

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是一个字典实例并发布了一系列字典

2 个答案:

答案 0 :(得分:5)

append是添加项目,而您尝试追加另一个数组(post是一个字典数组)。您可以使用+=运算符:

posts += newPost

或使用extend方法(相当于+=运算符):

posts.extend(newPost)

或单独添加元素:

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

答案 1 :(得分:0)

如果您希望每个帖子都是帖子和参数数组:

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

此外,您可以定义帖子和附件的类型,而无需创建空对象:

var post:Dictionary<String,AnyObject>
var attachment:Dictionary<String,AnyObject>