GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

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 Essential Developer.

SPONSORED Transform your career with the iOS Lead Essentials. Unlock over 40 hours of expert training, mentorship, and community support to secure your place among the best devs. Click for early access to this limited offer and a FREE crash course.

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.