Skip to content

Instantly share code, notes, and snippets.

@toineheuvelmans
Created January 26, 2017 09:53
Show Gist options
  • Save toineheuvelmans/e205ce4d1c5cadde85d9aefa53fc22da to your computer and use it in GitHub Desktop.
Save toineheuvelmans/e205ce4d1c5cadde85d9aefa53fc22da to your computer and use it in GitHub Desktop.
// (Swift 3)
// Given a number of functions that all have the signature () -> T?
// I want to try each of them, until I have a result (i.e. a non-optional).
// For instance:
let f1: () -> Int? = { _ in nil }
let f2: () -> Int? = { _ in nil }
let f3: () -> Int? = { _ in 2 }
let f4: () -> Int? = { _ in 3 }
// You could of course do the following:
let r1 = f1() ?? f2() ?? f3() ?? f4()
// > r1: 2
// But that doesn't look very nice.
// Therefore, I made this:
func attempt<T, R>(_ sequence: T) -> U? where T:Sequence, T.Iterator.Element == ((Void)->R?) {
for att in sequence {
if let res = att() {
return res
}
}
return nil
}
// So that you can do this:
let r2 = attempt([f1, f2, f3, f4])
// > r2: 2
// Only downside is that you cannot pass any arguments... Maybe next time.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment