LAST CHANCE: Save 50% on all my Swift books and bundles! >>

SOLVED: Access control test question Day 11 STRUCTURES PART TWO

Forums > 100 Days of SwiftUI

Hello friends,

I am failing to understand why this code is not valid Swift.

struct Doctor {
    var name: String
    var location: String
    private var currentPatient = "No one"
let drJones = Doctor(name: "Esther Jones", location: "Bristol")

CurrentPatient is initialized inside the struct, and no one outside of the struct is trying to access it. Am I missing something?

How is it any different than question 4

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

Thank you



Read the whole answer only to understand. Don't think of memorizing in one go. Break the question in parts( as many u wish.. ... Now go through one part and learn it loudly. Now check whether u have learned by hiding the answer. If yes: repeat processes 4 and 5 till u complete the answer.


In the first example, you are relying on the compiler-generated memberwise initializer, as you have not supplied an explicit initializer. The compiler will attempt to create a method that initializes all properties. But with a private property in your struct, the compiler cannot generate a memberwise init because it can't access the private property.

If you add something like this then you won't get an error any longer:

init(name: String, location: String) { = name
    self.location = location

In the second example, you only have a single private property and no non-private properties, so the compiler doesn't even try to create a memberwise init at all and thus doesn't choke and generate an error.


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 July 28th.

Click to save your free spot now

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.