Zonily Jame
Zonily Jame

Reputation: 5359

Append values to [String : AnyObject] or [String : String]

I want to append values to a variable of type [String : AnyObject] how do I do that? cause I can't do the ff.

var someObject:[String : AnyObject] = ["name":"John Diggle", "location":"Star City Prison"]

someObject.append(["work":"soldier"])        // does not work  (by that I mean there is no .append function like that of other collection types such as NSMutableArray and NSMutableDictionary
someObject = someObject + ["work":"soldier"] // does not work

I'm finding a way to make easier parameters for Alamofire since Alamofire.request uses [String : AnyObject]

Upvotes: 3

Views: 8714

Answers (3)

Akbar Khan
Akbar Khan

Reputation: 2417

Initialize dictionary

var dic = [String: Any]()

or

var dic : [String: Any] = ["firstName": "John", "lastName": "Doe"]

Append value

dic["age"] = 25

Update Value

dic.updateValue("Jan", forKey: "firstName")

Upvotes: 1

Muzahid
Muzahid

Reputation: 5186

The data type you have mentioned is called Dictionary. And Swift dictionary does not provide API append(_ newElement:). Dictionary is a type of hash table. Each entry in the table is identified using its key.

If you want to add new item (key,value), simply add new value under a new key like that:

object["Work"] = "Soldier"

For more information read this doc Dictionary

Upvotes: 15

matt
matt

Reputation: 535240

Try this:

someObject["work"] = "soldier" as NSString

The problem we're trying to solve is that we don't get automatic bridging from String to NSString (NSString is an AnyObject, but String is not), so we have to cross the bridge ourselves by casting.

Upvotes: 3

Related Questions