Last active
August 29, 2015 14:06
-
-
Save rosskimes/638d4e461dca17e1147e 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
public extension Array { | |
/** | |
:param: transform The closure to apply to each value of `self`. | |
:returns: `Array` containing the results of mapping `transform` over `self` and removing all `nil` values. | |
*/ | |
public func filterMap<U>(transform: (T) -> U?) -> [U] { | |
var mapped = [U]() | |
for item in self { | |
if let unwrapped = transform(item)? { | |
mapped.append(unwrapped) | |
} | |
} | |
return mapped | |
} | |
} | |
public extension Dictionary { | |
/** | |
Create a `Dictionary` from an `Array` of `Elements` (`Elements` are `(Key, Value)` pairs). | |
*/ | |
public init(elements: [Element]) { | |
self.init() | |
for (k, v) in elements { | |
self[k] = v | |
} | |
} | |
/** | |
:param: transform The closure to apply to each value of `self`. | |
:returns: `Dictionary` containing the results of mapping `transform` over `self.values`. Keys are the same as 'self'. | |
*/ | |
public func map<K: Hashable, V>(transform: Element -> (K, V)) -> [K: V] { | |
return Dictionary<K, V>(elements: Swift.map(self, transform)) | |
} | |
/** | |
:param: includeElement The closure that determines if a given `Element` should be included in the output array. | |
:returns: `Dictionary` containing the elements of `self`, in order, that satisfy the predicate includeElement. | |
*/ | |
public func filter(includeElement: Element -> Bool) -> [Key: Value] { | |
return Dictionary(elements: Swift.filter(self, includeElement)) | |
} | |
/** | |
:param: transform The closure to apply to each value of `self`. | |
:returns: `Dictionary` containing the results of mapping `transform` over `self.values` and removing all keys for `nil` values. Non-nil keys are the same as 'self'. | |
*/ | |
public func filterMap<U>(transform: (Key, Value) -> (Key, U?)) -> [Key: U] { | |
var mapped = self.map { transform( $0, $1) } | |
var filtered = mapped.filter { $1 != nil} | |
return filtered.map { ($0, $1!) } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment