Skip to content

Instantly share code, notes, and snippets.

@JadenGeller
Last active August 29, 2015 14:16
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JadenGeller/49872da24dd8de826eae to your computer and use it in GitHub Desktop.
Save JadenGeller/49872da24dd8de826eae to your computer and use it in GitHub Desktop.
Swift Attempt Function
/*
* attempt takes a function that does not accept optional values
* and returns a new function that will work as usual with non-optional values
* and return nil when passed an optional value
*/
func attempt<T,U>(f: T -> U)-> T? -> U? {
return { y in
if let x = y {
return f(x)
}
else {
return nil
}
}
}
// Example
var arr = [3.2, 2.1, 1.0]
let x: Double? = 5.0 // Optional value
// tl;dr
attempt(arr.append)(x)
let y = attempt(sqrt)(x)
//
// Motivation
//
// No return value
arr.append(x) // Error
if let x = x { arr.append(x) } // Annoying
if (x != nil) { arr.append(x!) } // Gross
attempt(arr.append)(x) // >> Yay! <<
// Return value
let y = sqrt(x) // Error
if let x = x { let y = sqrt(x) } // Annoying
let y = (x != nil) ? sqrt(x!) : nil // Gross
let y = attempt(sqrt)(x) // >> Yay! <<
// Note that the "annoying" example for 'return value' is especially
// horrible because all code that uses y must be within the brackets
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment