Created
December 2, 2025 21:34
-
-
Save jakehawken/510e66a0ab0bc167971977217516970b to your computer and use it in GitHub Desktop.
One-liner functions for adding an value to a dictionary if it's non-nil
This file contains hidden or 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
| extension Dictionary { | |
| func addingIfNonNil(key: Key, value: Value?) -> Self { | |
| guard let value else { | |
| return self | |
| } | |
| var copy = self | |
| copy[key] = value | |
| return copy | |
| } | |
| func addingIfNonNil(_ values: [Value?], keyGenerator: (Value) -> Key) -> Self { | |
| guard !values.isEmpty else { | |
| return self | |
| } | |
| var copy = self | |
| values.forEach { value in | |
| if let value { | |
| copy[keyGenerator(value)] = value | |
| } | |
| } | |
| return copy | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment