cmii
cmii

Reputation: 3636

Add a dictionary to an array in Swift

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

Upvotes: 0

Views: 11492

Answers (2)

Krys Jurgowski
Krys Jurgowski

Reputation: 2911

If you want each post to be an array of post and argument:

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

Also, you can define the type for post and attachment without creating empty objects:

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

Upvotes: 0

Antonio
Antonio

Reputation: 72760

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)

Upvotes: 5

Related Questions