Skip to content

Instantly share code, notes, and snippets.

@jakehawken
Created December 2, 2025 21:34
Show Gist options
  • Select an option

  • Save jakehawken/510e66a0ab0bc167971977217516970b to your computer and use it in GitHub Desktop.

Select an option

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
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