Skip to content

Instantly share code, notes, and snippets.

@vesic
Created November 28, 2022 23:04
Show Gist options
  • Save vesic/944fc9a9ec4c9557835b2c79e28ed282 to your computer and use it in GitHub Desktop.
Save vesic/944fc9a9ec4c9557835b2c79e28ed282 to your computer and use it in GitHub Desktop.
// FUNCTION WITH NO NAME
// SPECIAL CASES OF CLOSURE
//let sum = { (a: Int, b: Int) -> Int in
// return a + b
//}
//let result = sum(4, 2)
// "CLOSE OVER"
// ACCESS, STORE & MANIPULATE SURROUNDING CONTEXT
// VALUES CAPTURED BY THE CLOSURE
var counter = 0
let increment = { counter += 1 }
increment()
increment()
increment()
increment()
increment()
counter
func counting() -> (() -> Int) {
var counter = 0
let increment: () -> Int = {
counter += 1
return counter
}
return increment
}
let counter1 = counting()
let counter2 = counting()
counter1()
counter2()
counter1()
counter1()
counter2()
// DESIGNED TO BE LIGHTWEIGHT
// NO NAMING OVERHEAD
// MANY WAYS TO SHORTEN SYNTAX
var sum = { (a: Int, b: Int) -> Int in
return a + b
}
sum = { (a: Int, b: Int) -> Int in
a + b
}
sum = { (a, b) in a + b }
sum = { $0 + $1 }
func greet(hello: () -> Void) {
hello()
}
greet {
print("hello world")
}
let students: Set = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
let sortedStudents = students.sorted()
students.sorted {
$0.count > $1.count
}
var prices = [1.5, 10, 4.99, 2.30, 8.19]
let largePrices = prices.filter {
return $0 > 5
}
let salePrices = prices.map {
return $0 * 0.9
}
let stock = [1.5:5, 10:2, 4.99:20, 2.30:5, 8.19:30]
let stockSum = stock.reduce(0) {
return $0 + $1.key * Double($1.value)
}
import UIKit
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
print("Hello world!")
}
let url = URL(string: "https://www.example.com/")!
let task = URLSession.shared.dataTask(with: url) { data, response, error in
if let data = data {
let string = String(data: data, encoding: .utf8)!
print(string)
}
}
task.resume()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment