How to add elements to a dictionary in Swift

2 Answers

0 votes
import Foundation

var dict = ["swift": 3, "c": 4, "python": 2]

print("Dictionary(Before Adding):", dict)

// Adding new key-value pairs
dict["java"] = 16
dict["c++"] = 5
dict["php"] = 10

print("Dictionary(After Adding):", dict)



/*
run:

Dictionary(Before Adding): ["python": 2, "swift": 3, "c": 4]
Dictionary(After Adding): ["c": 4, "java": 16, "swift": 3, "c++": 5, "php": 10, "python": 2]

*/

 



answered Aug 5, 2025 by avibootz
0 votes
import Foundation

var dict = ["swift": 3, "c": 4, "python": 2]

print("Dictionary(Before Adding):", dict)

// Adding new key-value pairs
dict.updateValue(16, forKey: "Java")
dict.updateValue(5, forKey: "c++")
dict.updateValue(10, forKey: "php")

print("Dictionary(After Adding):", dict)



/*
run:

Dictionary(Before Adding): ["python": 2, "swift": 3, "c": 4]
Dictionary(After Adding): ["Java": 16, "python": 2, "c": 4, "c++": 5, "php": 10, "swift": 3]

*/

 



answered Aug 5, 2025 by avibootz
...