Skip to content

Instantly share code, notes, and snippets.

@lukaskubanek
Created October 13, 2015 07:28
Show Gist options
  • Save lukaskubanek/c7a07c0d7149ea92ccf9 to your computer and use it in GitHub Desktop.
Save lukaskubanek/c7a07c0d7149ea92ccf9 to your computer and use it in GitHub Desktop.
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