After going 5 days straight non-stop. I decided to take a break on the 6th day for a recap, and also to catch my breath. There is so much information to take in.
Introduction
This is my sixth day of learning SwiftUI using Paul Hudson's 100 Days of SwiftUI challenge.
Today I learned how to write and use basic closures. Quite confusing initially but I think I've figured out the basics to get started with.
Summary
- Closures
// Declaring a closure
let lol = {
print("I'm laughing out loud")
}
// Invoking the anonymous closure like a regular function
lol()
// Closure can also accept parameters like functions. To make a closure accept parameters, list them inside parentheses just after the opening brace, then write "in" so that Swift knows the main body of the closure is starting.
let sentence = { (action : String) in
print("I'm \(action) out loud")
}
// Always remember that you don’t use parameter labels when calling closures
sentence("thinking")
sentence("laughing")
// Closure can also return values
// So we need to use -> "The_return_type" before in, then use return just like a normal function:
let expression = { (action : String) -> String in
return "I'm \(action) out loud"
}
// Again, you don’t use parameter labels when calling closures
let yelling = expression("yelling")
print(yelling)
// For the last time, remember you don’t use parameter labels when calling closures
let smiling = expression("smiling")
print(smiling)
- Using closures as a parameters to a function - Closures can be used as integers and strings.
let text = {
print("Followed by a sample text")
}
// When you use a closure that returns nothing as a parameter to a function, we would specify the parameter type as () -> Void. That means it “accepts no parameters, and returns Void(nothing)”
// Let's declare a paragraph function that accepts a parameter called "word"...that is a closure
func paragraph(word : () -> Void) {
print("This is the first text")
word()
print("This is the last text")
}
// Calling the paragraph function, and passing the closure
paragraph (word : text)
// Another example of closure as a parameter to cement the learning
let something = {
print("I just said something!")
}
func saySomething(sentence : () -> Void) {
print("Kenny, will you say something?")
sentence()
print("Glad you did!")
}
// calling the function passing in the closure as a parameter
saySomething(sentence : something)
// If the last parameter to a function is a closure, Swift lets us use special syntax called trailing closure syntax.
saySomething() {
print("This will replace the sentence in the closure")
}
// If there are no other parameters, we can get rid of the parenthesis
saySomething {
print("This will ALSO replace the sentence in the closure")
}
Thanks for reading🙏🏿.
You can find me on Twitter @RealKennyEdward
I'm on to Day7!
Top comments (0)