Skip to content

Instantly share code, notes, and snippets.

@kentliau
Last active June 12, 2021 15:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kentliau/c2bac7c369df2150e8b5db906cac7587 to your computer and use it in GitHub Desktop.
Save kentliau/c2bac7c369df2150e8b5db906cac7587 to your computer and use it in GitHub Desktop.
Type Inference in Swift’s Closure
// Credit: Stanford’s Developing iOS8 App with Swift Course (Available via iTunes U Course via Apple Swift Portal)
// This function itself accept a closure, and return nothing
func performOperation(operation: (Double, Double) -> Double) {
println(operation(20.0,10.0))
}
// Thanks to type inference, we can further simplify the following
// function call that accept a well defined closure as argument
performOperation({ (op1: Double, op2: Double) -> Double in
return op1 * op2
})
// It knows it must take two double as argument,
// so we don't need to specify it
performOperation({ (op1, op2) -> Double in
return op1 * op2
})
// Because it must also return a double,
// we don't specify it as well
performOperation({ op1, op2 in
return op1 * op2
})
// We can write it in one line
performOperation({ op1, op2 in return op1 * op2 })
// It knows it must return a double,
// if the last statement is just a expression,
// it will know it has to be return
performOperation({ op1, op2 in op1 * op2 })
// You don't even need to name your parameter of the closure,
// you can just use $0, $1, $2 and so on
performOperation({ $0 * $1 })
// Since the last argument of this function is a closure,
// you can move it out of the parentheses
performOperation() { $0 * $1 }
// Since it is the only argument,
// we don't even need a pair of parentheses,
// it understand it is a function call with a closure as argument
performOperation { $0 * $1 }
// Try the built in sorted function
sorted([8,2,9,3,7,4,3,4,5]) { $0 < $1 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment