snapchatdotcom snapchatdotcom - 4 months ago 12
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

String
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"]
print(parent)

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

Answer

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"]
Comments