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 learningSwiftUI usingPaul Hudson's100 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 closureletlol={print("I'm laughing out loud")}// Invoking the anonymous closure like a regular functionlol()// 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.letsentence={(action:String)inprint("I'm\(action) out loud")}// Always remember that you don’t use parameter labels when calling closuressentence("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:letexpression={(action:String)->Stringinreturn"I'm\(action) out loud"}// Again, you don’t use parameter labels when calling closuresletyelling=expression("yelling")print(yelling)// For the last time, remember you don’t use parameter labels when calling closuresletsmiling=expression("smiling")print(smiling)
- Using closures as a parameters to a function - Closures can be used as integers and strings.
lettext={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 closurefuncparagraph(word:()->Void){print("This is the first text")word()print("This is the last text")}// Calling the paragraph function, and passing the closureparagraph(word:text)// Another example of closure as a parameter to cement the learningletsomething={print("I just said something!")}funcsaySomething(sentence:()->Void){print("Kenny, will you say something?")sentence()print("Glad you did!")}// calling the function passing in the closure as a parametersaySomething(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 parenthesissaySomething{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)
Subscribe
For further actions, you may consider blocking this person and/orreporting abuse