Last active
March 28, 2023 07:40
-
-
Save asmallteapot/5bef591b22ef59f7a27bd1d3a0a8ff8f to your computer and use it in GitHub Desktop.
Swift: Append an element to an array in a dictionary value, creating the array/value if needed
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
extension Dictionary where Value: RangeReplaceableCollection { | |
public mutating func append(element: Value.Iterator.Element, toValueOfKey key: Key) -> Value? { | |
var value: Value = self[key] ?? Value() | |
value.append(element) | |
self[key] = value | |
return value | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var books: [String: [String]] = [ | |
"Phillip K Dick": [ | |
"Do Androids Dream of Electric Sheep?", | |
"The Man in the High Castle", | |
], | |
"Cory Doctorow": [ | |
"Down and Out in the Magic Kingdom", | |
"Makers", | |
] | |
] | |
books.append(element: "Eastern Standard Tribe", toValueOfKey: "Cory Doctorow") | |
books | |
/* | |
[ | |
"Phillip K Dick": [ | |
"Do Androids Dream of Electric Sheep?", | |
"The Man in the High Castle", | |
], | |
"Cory Doctorow": [ | |
"Down and Out in the Magic Kingdom", | |
"Makers", | |
"Eastern Standard Tribe", | |
] | |
] | |
*/ | |
books.append(element: "Parable of the Sower", toValueOfKey: "Octavia Butler") | |
books | |
/* | |
[ | |
"Phillip K Dick": [ | |
"Do Androids Dream of Electric Sheep?", | |
"The Man in the High Castle", | |
], | |
"Cory Doctorow": [ | |
"Down and Out in the Magic Kingdom", | |
"Makers", | |
"Eastern Standard Tribe", | |
], | |
"Octavia Butler": [ | |
"Parable of the Sower", | |
] | |
] | |
*/ | |
@asmallteapot actully it's greate extention but when i try to use it that's what i found i hope if u help me
Result of call to 'append(element:toValueOfKey:)' is unused
@asmallteapot actully it's greate extention but when i try to use it that's what i found i hope if u help me
Result of call to 'append(element:toValueOfKey:)' is unused
It just returns the value you added to the dictionary value part. You can silence that warning using these 2 ways:
1- Ignore the result by adding _ = in front of the function call
2- Add @discardableResult to the declaration of the function to silence the compiler
Saved my day thankss!!
if you want add element in [String] to your dictionary like [String : [String]] use methods @AtishPapa. That methods helped me
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Actually there's a one liner for that (since Swift 4.0) 😉
books["Cory Doctorow", default: []].append("Whatever")