Created
July 21, 2023 09:42
-
-
Save josetapadas/98c133674ec7d8dc0099e8bf2a827d41 to your computer and use it in GitHub Desktop.
Swift Closures
This file contains hidden or 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
import UIKit | |
var simpleClosure = { | |
print("Hello from a closure!") | |
} | |
simpleClosure() | |
var wrapperColosure = { | |
let outerVariable = "Jon" | |
let innerClosure = { | |
print("Hello \(outerVariable)!") | |
} | |
innerClosure() | |
} | |
wrapperColosure() | |
var greeterClosure = {(name: String) -> String in | |
"Hello \(name)!" | |
} | |
greeterClosure("Jon") | |
var doubleAmount = {(number: Int) -> Int in | |
number * 2 | |
} | |
print(doubleAmount(2)) | |
func computation(n: Int, closure: (_ num: Int) -> Int) { | |
print("The original value is \(n)") | |
print("We apply a extra computation...") | |
let newValue = closure(n) | |
print("We end our computation: \(newValue)") | |
} | |
computation(n: 2) { (num: Int) -> Int in | |
num + num | |
} | |
computation(n: 3) { num in | |
num * 3 | |
} | |
computation(n: 4) { | |
$0 * 4 | |
} | |
func multiply(multiplier: Int) -> (Int) -> Int { | |
let mul = multiplier | |
return { num in | |
return mul * num | |
} | |
} | |
var timesTwo = multiply(multiplier: 2) | |
print(timesTwo(5)) | |
var timesTen = multiply(multiplier: 10) | |
print(timesTen(5)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment