UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Day 18: using self in closures

Forums > 100 Days of SwiftUI

@foosm  

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) {
        Text("\(self.tipPercentages[$0])%")
    }
}

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)?

Thanks

4      

@BSM  

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!

BSM

3      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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.