Last active
June 11, 2023 21:25
-
-
Save adam-zethraeus/d12fca13b18774a58a6f6c8667890e72 to your computer and use it in GitHub Desktop.
Swift Collection Extensions
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
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