NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

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!



Hacking with Swift is sponsored by Play

SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!

Click to learn more about Play!

Sponsor Hacking with Swift and reach the world's largest Swift community!

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.