Skip to content

Instantly share code, notes, and snippets.

@josetapadas
Created July 21, 2023 09:42
Show Gist options
  • Save josetapadas/98c133674ec7d8dc0099e8bf2a827d41 to your computer and use it in GitHub Desktop.
Save josetapadas/98c133674ec7d8dc0099e8bf2a827d41 to your computer and use it in GitHub Desktop.
Swift Closures
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