Created
October 13, 2015 07:28
-
-
Save lukaskubanek/c7a07c0d7149ea92ccf9 to your computer and use it in GitHub Desktop.
FailableMap.swift
This file contains hidden or 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
// | |
// FailableMap.swift | |
// | |
// Created by Lukas Kubanek on 06/10/15. | |
// Copyright © 2015 Lukas Kubanek. All rights reserved. | |
// | |
public extension Array { | |
/// Maps the transform over `self` and if **all** calls return a non-nil result it returns | |
/// an Array of the results or `nil` otherwise. | |
public func failableMap<T>(transform: Element throws -> T?) rethrows -> [T]? { | |
return try reduce([]) { accum, element in | |
if let accum = accum, let transfomedElement = try transform(element) { | |
return accum + [transfomedElement] | |
} else { | |
return nil | |
} | |
} | |
} | |
} | |
public extension Dictionary { | |
public func failableMapValues<T>(transformValue: Value throws -> T?) rethrows -> [Key: T]? { | |
return try reduce([:]) { (accum: [Key: T]?, element: (key: Key, value: Value)) in | |
if let accum = accum, let transformedValue = try transformValue(element.value) { | |
return accum + [element.key: transformedValue] | |
} else { | |
return nil | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment