Skip to content

Instantly share code, notes, and snippets.

@adam-zethraeus
Last active June 11, 2023 21:25
Show Gist options
  • Save adam-zethraeus/d12fca13b18774a58a6f6c8667890e72 to your computer and use it in GitHub Desktop.
Save adam-zethraeus/d12fca13b18774a58a6f6c8667890e72 to your computer and use it in GitHub Desktop.
Swift Collection Extensions
extension Collection {
func compact<E>() -> [E] where E? == Element {
compactMap { $0 }
}
}
extension Collection {
func indexed<Key: Hashable>(by path: KeyPath<Element, Key>)
-> [Key: Element]
{
reduce(into: [Key: Element]()) { acc, curr in
acc[curr[keyPath: path]] = curr
}
}
}
#if canImport(OrderedCollections)
import OrderedCollections
extension Collection {
func orderedIndexed<Key: Hashable>(by path: KeyPath<Element, Key>)
-> OrderedDictionary<Key, Element>
{
reduce(into: OrderedDictionary<Key, Element>()) { acc, curr in
acc[curr[keyPath: path]] = curr
}
}
}
#endif
extension Collection {
func at(index: Index) -> Element? {
if endIndex > index {
return self[index]
} else {
return nil
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment