Created
June 23, 2017 15:35
-
-
Save NoahPeeters/ce06a0b23e409ff611c73f5803eaccff 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
extension Sequence { | |
public func filterMap<T>(map: (Self.Iterator.Element) throws -> (Bool, T)) rethrows -> [T] { | |
var array : [T] = [] | |
for element in self { | |
do { | |
let (result, value) = try map(element) | |
if result { | |
array.append(value) | |
} | |
} | |
} | |
return array | |
} | |
public func filterMap<T>(includeElement: (Self.Iterator.Element) throws -> Bool, map: (Self.Iterator.Element) throws -> T) rethrows -> [T] { | |
var array : [T] = [] | |
for element in self { | |
do { | |
if try includeElement(element) { | |
array.append(try map(element)) | |
} | |
} | |
} | |
return array | |
} | |
} | |
print((0...10).filterMap { return ($0 % 2 == 0, $0 * 2) }) | |
// prints [0, 4, 8, 12, 16, 20] | |
print( | |
(0...10).filterMap( | |
includeElement: { return $0 % 2 == 0 }, | |
map: { return $0 * 4 } | |
) | |
) | |
// prints [0, 8, 16, 24, 32, 40] | |
print([nil, 1, 4, nil, 6].filterMap(includeElement: { $0 != nil }, map: { $0! + 1 })) | |
// prints [2, 5, 7] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment