snapchatdotcom snapchatdotcom - 7 months ago 22
Swift Question

Adding multiple values into a single key in swift?

When I try to add multiple values to the key, my value gets overridden by the last value I assigned to the key. I tried adding brackets between the value

of my [String: [String]] key-value pair. I did that to hopefully achieve the effect to add multiple values into that key.

import UIKit

var parent = [String: [String]]()
parent["parent"] = ["Tommy Turner", "Wolfgang Motart"]
parent["parent"] = ["Bobby Bushe"]

// How can I add multiple values into the parent key like this:
// ["parent": "Tommy Turner", "Wolgang Motart", "Bobby Bushe"]


Since the type of parent["parent"] is array of string, you can use append function for adding one or multiple elements. Try this.

var parent = [String: [String]]()
parent["parent"] = ["Tommy Turner", "Wolfgang Motart"]
parent["parent"]?.append("bob") // append one element to become ["Tommy Turner", "Wolfgang Motart", "bob"]
parent["parent"]?.appendContentsOf(["hello", "world"]) // append collection
print(parent["parent"]!) // ["Tommy Turner", "Wolfgang Motart", "bob", "hello", "world"]