WWDC24 SALE: Save 50% on all my Swift books and bundles! >>

Day 18: using self in closures

Forums > 100 Days of SwiftUI


hi all,

At day 18, there is a mention of closures and using $0 as shorthand syntax for closure parameters... the author follows with the mention of using 'self in self.tipPercentages'...

Picker("Tip percentage", selection: $tipPercentage) {
    ForEach(0 ..< tipPercentages.count) {

I do not understand why is self needed in this case whereas self is not used in the line just above in 'ForEach(0 ..< tipPercentages.count)'. What is the difference between this 2 access of the instance property (tipPercentages)?




First, anyone please correct me if I am wrong.

When you choose an @State variable for your selection, you need to mark it with a $ to let swiftUI know that you want that variable to be observed and changed based on the users choice. In that case, you dont need the self keyword. but when you read the value of that variable, it does need self. self is there to make sure you use the variable name of that struct/class. It is mostly used in initilisers. Maybe this short article explains it better. SwiftUI still has a lot of self's in its code for ios 13, but with the new swiftUI 2 for ios 14, you can safly remove that self without xcode complaining and not building our code.

hope it helps!



Save 50% in my WWDC sale.

SAVE 50% To celebrate WWDC24, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.