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

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

AM

3      

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.

3      

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) {
    self.name = 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.

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.