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

What's the difference between these two structs and their private properties?

Forums > 100 Days of SwiftUI

Currently on Day 11 and in the test I noticed two different structs that looked almost identitical, except one of them has a private property with a default value and the other struct has a private property with a named type. I can access the first struct's property but I can't with the second. Why is one accessible and the other isn't when they're both labeled as private?

struct Contributor {
    private var name = "Anonymous"
let paul = Contributor()

// The other struct

struct FacebookUser {
    private var privatePosts: [String]
    public var publicPosts: [String]
let user = FacebookUser()


I'm not quite sure what you mean by "I can access the first struct's property but I can't with the second." In the example you give, you aren't accessing any properties from either of the structs.

I think what you are trying to say is that you can create a Contributor but not a FacebookUser even though both have private properties.

You can create a Contributor because name has a default value so you don't need to supply one in an initializer. Swift is unable to create a memberwise initializer for you because of the private property, but you don't need one here since there are no other properties. So you can just create a Contributor using the bare init() initializer.

You can't create a FacebookUser in this example for 2 reasons:

  1. You cannot assign a value to privatePosts due to its private access level. Swift is unable to automatically generate a memberwise initializer for you because of that and you have no other explicit initializer in which you can assign a value to privatePosts.

  2. You don't assign a value to publicPosts

To get this code to work, you would need to add something like this:

init(privatePosts: [String], publicPosts: [String]) {
    self.privatePosts = privatePosts
    self.publicPosts = publicPosts

(There are other ways you could construct the struct and its initializer to accomplish the same thing. This is just one example.)


Hacking with Swift is sponsored by Superwall

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Learn More

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

Reply to this topic…

You need to create an account or log in to reply.

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.