Created
February 2, 2016 19:01
-
-
Save DeFrenZ/852168c04292eab9ef25 to your computer and use it in GitHub Desktop.
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
//MARK: - ??= | |
infix operator ??= { | |
associativity right | |
precedence 90 | |
assignment | |
} | |
func ??= <Wrapped> (inout optional: Wrapped?, @autoclosure defaultValue: () throws -> Wrapped?) rethrows { | |
optional = try optional ?? defaultValue() | |
} | |
extension SequenceType { | |
public func indexBy <IndexValue: Hashable> (indexingValue: (Generator.Element) -> IndexValue) -> [IndexValue: Generator.Element] { | |
var indexed: [IndexValue: Generator.Element] = [:] | |
for element in self { | |
let key = indexingValue(element) | |
indexed[key] = element | |
} | |
return indexed | |
} | |
public func groupBy <GroupingValue: Hashable> (groupingValue: (Generator.Element) -> GroupingValue) -> [GroupingValue: [Generator.Element]] { | |
var grouped: [GroupingValue: [Generator.Element]] = [:] | |
for element in self { | |
let key = groupingValue(element) | |
grouped[key] ??= [] | |
grouped[key]?.append(element) | |
} | |
return grouped | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment