Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.