Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
FailableMap.swift
//
// 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