Day 5 of HackingWithSwift's 100 days of SwiftUI. Today I learnt about closures.
You can think of closures as nameless functions that you can assign to a variable or pass as a parameter into a function.
Closures are mostly used to perform an action later in the future when a condition is met. For example, when a file downloads successfully, store its content into a database.
let helloWorldClosure = {
print("hello")
}
helloWorldClosure()
The code above creates a closure that prints "Hello" and assigns the closure to the helloWorldClosure variable. You can then simply call the closure as you would a function.
let greatClosure = { (name: String) in
print("Hello \(name)")
}
greatClosure("Sanmi")
The code above creates a closure that takes a single parameter and greats the user. Please note you don't need to add a label when calling a closure.
let addClosure = { (first: Int, second: Int) -> Int in
return first + second
}
let sum = addClosure(1,2)
The code above creates a closure that takes two numbers as parameters and returns the sum of the numbers.
Like I said before you can pass closures as a parameter into a function.
let saveFile = {
//code to save file
}
func downloadFile(imageUrl, onSuccess: () ->) {
//code to download file
if(downloadSuccessfull){
onSuccess()
}
}
downloadFile(imageUrl: "Instagram", onSuccess: saveFile)
The code above creates a closure that saves a file downloaded from the internet. This closure is passed into the downloadFile
function. This downloadFile
function downloads a file from the internet and calls the save file closure if the file was downloaded successfully.
If you are interested in taking the challenge, you can find it at https://www.hackingwithswift.com/100/swiftui
See you tomorrow ;)
Top comments (0)