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

SOLVED: Why do memberwise initializers allow for direct access to properties of structs?

Forums > 100 Days of SwiftUI

Edit: This question involves an assumption that was incorrect on my part. You should probably just ignore this!

This is somewhat a philosophical question, but I was just wondering if anyone would have the answer to this. Why do memberwise initializers allow you to directly access properties of structs?

I'm wondering this because of how they work with private properties.

For example, if I had:

struct Apple {
  var color: String
  var price: Double
}

This will create a memberwise initializer that will allow me to directly access these properties and pass in values:

let apple = Apple(color: "Red", price: 4.25)

Comparatively, I could create a similar struct with a custom initializer:

struct Pear {
  var color: String
  var price: Double

  init(color: String, price: Double) {
    self.color = color
    self.price = price
  }
}

This will use my custom initializer and indirectly pass in values to my properties:

let apple = Pear(color: "Red", price: 4.25)

This will really just do the same thing, except that the properties are being indirectly accessed by init() parameters. This has the added benefit of being able to mark my properties as private, however. Because of this reason alone, I started to question why memberwise initializer don't work this way. Wouldn't it be more beneficial for memberwise initializers to indirectly access properties so I could mark the properties of Apple as private? What's the benefit of direct access to properties for the memberwise initializer?

1      

Please see my update to your other thread.

1      

Ah! So the initializers for these two are actually the exact same. There is no "direct" access.

1      

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.