Swift – Add a dictionary to an array in Swift

arraysdictionaryswift

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 ?

UPDATE / SOLVED

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'

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

Best Solution

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)

or add elements individually:

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