Skip to content

Instantly share code, notes, and snippets.

@pauljohanneskraft
Last active June 9, 2016 19:01
Show Gist options
  • Save pauljohanneskraft/6ee101e715ed2601b3b8152bfb1b90db to your computer and use it in GitHub Desktop.
Save pauljohanneskraft/6ee101e715ed2601b3b8152bfb1b90db to your computer and use it in GitHub Desktop.
CatchLoop - catches all Errors being thrown and safes either the return value or the thrown error in a Dictionary

CatchLoop

The function can be used to iterate over a sequence (implementing Sequence-protocol).

It returns a dictionary containing either the returned value or a thrown error.

func catchloop<I : Hashable, S: Sequence where S.Iterator.Element == I>
(_ range: S, _ f: (I) throws -> Any) -> [I:Any] {
var dict = [I:Any]()
for i in range {
do {
let e = try f(i)
dict[i] = e
} catch let e { dict[i] = e }
}
return dict
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment