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

Explanation of "Swift doesn’t let us create one stored property that refers to other stored properties" please?

Forums > SwiftUI

Could someone elaborate on this quote please?

Swift doesn’t let us create one stored property that refers to other stored properties, because it would cause problems when the object is created. This means trying to create a TextField bound to a local property will cause problems.

I'm afraid I neither understand what it's trying to say exactly, nor why what it's talking about isn't allowed.

3      

I think the examples on that page could be better... After defining: let motto1 = ... let motto2 = ... we might want to define let mottos = VStack { motto1 motto2 }

but we can't, because the initialiser needs to implicitly use self to refer to the two properties and self does not exist until the initialiser has completed.

This has probably confused you more still, but it is a matter of understanding how the compiler "thinks" (as well as the specific terms, like 'local', 'property' and 'local property')

3      

So if we tried to write

struct ContentView: View {
    let nameFieldLabel = "Enter your name"
    @State private var name = ""
    var nameField = TextField(nameFieldLabel, text: $name)

    var body: some View {
        nameField
    }
}

we'd get an error because the fourth line here is implicitly var nameField = TextField(self.nameFieldLabel, text: $self.name) but self isn't available at the time the initializer declares and assigns nameField?

If I got that right then your answer didn't confuse me more still but rather, on the contrary, was very helpful in clearing this up for me! ☺️ If not, please help me understand what I still got wrong here.

3      

Your explanation makes sense to me - do you get an error saying something about self and initialisers?

I think you have got it.

3      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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.