Skip to content

Instantly share code, notes, and snippets.

@frakingFrank
Created November 13, 2017 09:27
Show Gist options
  • Save frakingFrank/2285d270dd85f21aa8cf5ea1a3e016e9 to your computer and use it in GitHub Desktop.
Save frakingFrank/2285d270dd85f21aa8cf5ea1a3e016e9 to your computer and use it in GitHub Desktop.
Here is an example of nested Functions. The first function solves if two numbers are divisible, if not it returns nil. The second function makes an optional binding and return the answer. In this function there is the return of the first function as parameter.
func divideIfWhole(_ value: Int, by divisor: Int) -> Int? {
var answer: Int? = 0
let divisible = value % divisor
switch divisible {
case 0:
answer = value / divisor
default:
answer = nil
}
return answer
}
let divisilbe = divideIfWhole
func isItDivisible(_ divisilbe: (Int, Int) -> Int?, _ a: Int, _ b: Int) {
if let result = divideIfWhole(a, by: b) {
print("Yep, it divides \(result) times")
}else{
print("Not divisible :[")
}
}
isItDivisible(divisilbe, 10, 2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment