Created
January 26, 2017 09:53
-
-
Save toineheuvelmans/e205ce4d1c5cadde85d9aefa53fc22da to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// (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