Map and collect errors

Updated
Jun 14, 2020 2:56 AM
Created
Jun 14, 2020 2:55 AM
Tags
Swift
Keywords

extension Sequence {
	public func mapAndCollectErrors<U>(_ transform: (Element) throws -> U) -> (results: [U], errors: [Error]) {
	    
	  var errors: [Error] = []
	  
	  let result = compactMap { element -> U? in
	    do {
	      return try transform(element)
	    } catch {
	      errors.append(error)
	      return nil
	    }
	  }
	      
	  return (result, errors)
	}
}