Skip to content

Instantly share code, notes, and snippets.

@DeFrenZ
Created February 2, 2016 19:01
Show Gist options
  • Save DeFrenZ/852168c04292eab9ef25 to your computer and use it in GitHub Desktop.
Save DeFrenZ/852168c04292eab9ef25 to your computer and use it in GitHub Desktop.
//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