TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

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()
print(paul)

// The other struct

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

3      

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

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!

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.