Created
November 17, 2017 17:14
-
-
Save drewmccormack/93f4666045f16b5c43f7b649f4671023 to your computer and use it in GitHub Desktop.
Use flatMap with multiple optional variables, ensuring all are non-nil before making a function call.
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
func flatMap<U, V, T>(_ i: U?, _ j: V?, block: (U, V)->T) -> T? { | |
var result: T? | |
if let i = i, let j = j { result = block(i,j) } | |
return result | |
} | |
func flatMap<U, V, W, T>(_ i: U?, _ j: V?, _ k: W?, block: (U, V, W)->T) -> T? { | |
var result: T? | |
if let i = i, let j = j, let k = k { result = block(i,j,k) } | |
return result | |
} | |
let i: Int? = 1 | |
let j: Int? = 2 | |
var k: Int? | |
let m: Int? = flatMap(i, j) { max($0, $1) } // i and j non-nil, so will execute | |
let n: Int? = flatMap(i, j, k) { $0+$1+$2 } // k is nil. Won't execute | |
flatMap(i,j) { print("i and j are non-nil: \($0) and \($1)") } // Will execute. No return |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment