How do I append to an immutable dictionary in Swift?
Unfortunately, this is a good question because the answer is "you can't". Not yet, anyway--others agree this should be added, because there's a Swift Evolution proposal for this (and some other missing Dictionary
features). It's currently "awaiting review", so you may see a merged()
method that's basically your +
operator in a future version of Swift!
In the meantime, you can use your solution to append entire dictionaries, or for one value at a time:
extension Dictionary {
func appending(_ key: Key, _ value: Value) -> [Key: Value] {
var result = self
result[key] = value
return result
}
}
How to add another dictionary entry to an existing dictionary to form a new dictionary (i.e. not append)
There is a built-in merging(_:uniquingKeysWith:)
function on Dictionary
that does exactly what you need.
let dictionary = [1:1]
let otherDictionary = [1:2, 2:3]
// This will take the values from `otherDictionary` if the same key exists in both
// You can use `$0` if you want to take the value from `dictionary` instead
let mergedDict = dictionary.merging(otherDictionary, uniquingKeysWith: { $1 })
If you want, you can easily define a +
operator for Dictionary
that uses the above function.
extension Dictionary {
static func + (lhs: Self, rhs: Self) -> Self {
lhs.merging(rhs, uniquingKeysWith: { $1 })
}
}
let addedDict = dictionary + otherDictionary
How do I append to an immutable dictionary in Swift?
Unfortunately, this is a good question because the answer is "you can't". Not yet, anyway--others agree this should be added, because there's a Swift Evolution proposal for this (and some other missing Dictionary
features). It's currently "awaiting review", so you may see a merged()
method that's basically your +
operator in a future version of Swift!
In the meantime, you can use your solution to append entire dictionaries, or for one value at a time:
extension Dictionary {
func appending(_ key: Key, _ value: Value) -> [Key: Value] {
var result = self
result[key] = value
return result
}
}
Swift - Append to NSMutableDictionary
Yes you are actually replacing the RSVPDirectory[firstLetter]
, overriding it every time with new tmp
.
What you are looking for is this:
//RSVPDirectory[firstLetter] = tmp //Replace this line with below code
let tempArray = RSVPDirectory[firstLetter] as? [AnyHashable]
tempArray?.append(tmp)
RSVPDirectory[firstLetter] = tmpArray
Here I have used a tempArray
because we want to mutate the array. Accessing it directly and trying to append new value will in-turn try to mutate an immutable value. So first I have got the array in the tempArray
and then after mutating the array I swapped it back in the dictionary with updated values.
Append to array in [String: Any] dictionary structure
The type of data[Items]
isn't Array
but actually Array<[String: Any]>
.
You could probably squeeze this into fewer steps, but I prefer the clarity of multiple steps:
var data: [String: Any] = [
"key1": "example value 1",
"key2": "example value 2",
"items": []
]
for index in 1...3 {
let item: [String: Any] = [
"key": "new value"
]
// get existing items, or create new array if doesn't exist
var existingItems = data["items"] as? [[String: Any]] ?? [[String: Any]]()
// append the item
existingItems.append(item)
// replace back into `data`
data["items"] = existingItems
}
How do I append an element to an array in a nested dictionary
You do it the same way Superman gets into his pants — one leg at a time. Pull out the array, append to it, put it back again:
var B = [ "EA" : [ "status": [["000": "OK"]]]]
B["EA"]?["status"] = [["000": "NOT OK"]]
print(B) // ["EA": ["status": [["000": "NOT OK"]]]]
if var arr = B["EA"]?["status"] {
arr.append(["001":"Good"])
B["EA"]?["status"] = arr
}
print(B) // ["EA": ["status": [["000": "NOT OK"], ["001": "Good"]]]]
How do you add a Dictionary of items into another Dictionary
You can define +=
operator for Dictionary
, e.g.,
func += <K, V> (left: inout [K:V], right: [K:V]) {
for (k, v) in right {
left[k] = v
}
}
How to add field to NSMutableDictionary Swift
Use Dictionary
in swift instead of NSDictionary
. Also, you need to give the type
while declaring the Dictionary
variable.
Try this:
var villages = [[String : Any]]()
var bars = [[String : Any]]()
var allBars = [[String : Any]]()
//And this
bars[2]["Distance"] = distanceInMiles
bars[2]
in the above code will only work if the array bars
has atleast 3 elements in it. Otherwise it will give "Array index out of bounds"
exception.
Swift - Adding value to an array inside a dictionary
EDIT: Thanks to Martin's comment. The snippet below is the the most succinct answer I can think of. I was initially coming at it from a wrong direction. and I was getting an error. See comments
struct Student {
let id: Int
let subject : String
}
var studentArray = [Student(id: 1, subject: "History"), Student(id: 2, subject: "History"), Student(id:1, subject: "Maths")]
typealias Subject = String
var dict : [Int: [Subject]] = [:]
for student in studentArray {
(dict[student.id, default: []]).append(student.subject)
}
print(dict)
Previous answers:
struct Student {
let id: Int
let subject : String
}
var studentArray = [Student(id: 1, subject: "History"), Student(id: 2, subject: "History"), Student(id:1, subject: "Maths")]
typealias Subject = String
var dict : [Int: [Subject]] = [:]
for student in studentArray {
var subjects = dict[student.id] ?? [String]()
subjects.append(student.subject)
dict[student.id] = subjects
}
print(dict)
Or you can do it this way:
struct Student {
let id: Int
let subject : String
}
var studentArray = [Student(id: 1, subject: "History"), Student(id: 2, subject: "History"), Student(id:1, subject: "Maths")]
typealias Subject = String
var dict : [Int: [Subject]] = [:]
for student in studentArray {
if let _ = dict[student.id]{
dict[student.id]!.append(student.subject)
}else{
dict[student.id] = [student.subject]
}
}
print(dict)
whichever you like
Related Topics
"Nsurl" Is Not Implicitly Convertible to "Url"; Did You Mean to Use "As" to Explicitly Convert
How to Perform a Curl Request in Swift
Stop Objects from Colliding Using Spritekit
Difference Between Packed VS Normal Data Type
How to Set Inputview for Textfield in Swiftui
How to Get the Download Progress with the New Try Await Urlsession.Shared.Download(...)
Case Insensitive Dictionary in Swift
How to Check If a String Contains Chinese in Swift
Swiftui - How to Use Oncommand with Nsmenuitem on MACos
Swiftui: Dismiss View Within MACos Navigationview
How to Filter Events Created for the Current Date in the Realm Swift
Why Do Servicesubscribercellularproviders Return Nil? (In iOS 12)
How to Use Environment Map in Arkit
Swiftui Navigationview Trying to Pop to Missing Destination (Monoceros)
Optional Chaining with Swift Strings
Sorting Nil Dates to the End of an Array
Trying to Use Keychainitemwrapper by Apple "Translated" to Swift