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

SOLVED: Why is the struct name required to access a static property?

Forums > 100 Days of SwiftUI

Is there any reason why the name of the struct is actually needed when I'm accessing a static property?

This causes an error:

struct Person {
    static var population = 0
    var name: String
    init(personName: String) {
        name = personName
        population += 1 // Static member 'population' cannot be used on instance of type 'Person'
    }
}

This does not cause an error:

struct Person {
    static var population = 0
    var name: String
    init(personName: String) {
        name = personName
        Person.population += 1
    }
}

It seems obvious that we can't use static members on an instance of our type, but I just don't really understand it syntactically. There is nothing to be confused with. Just reassurance/clarification would be great.

Thanks! :)

1      

It's just simple syntax to differentiate between a static and an instance variable. IMHO most languages use this syntax as well. With this syntax you could access the variable from outside the Person struct as well if it's public.

1      

Joe is thinking about static vars

I just don't really understand it syntactically.
There is nothing to be confused with. Just reassurance/clarification would be great.

Chances are quite high that this is not the right answer. But this is how I learned static vars. For others, let’s review how static vars can be used in code.

You defined a Person struct like this:

struct Person {
    static var population = 0  // count of all the Person objects
    var name: String // 
    init(named: String) {
        name = named
        Person.population += 1
    }
}

Now create two new Person objects in code.

let calvin = Person( named: “Calvin”)
let hobbes = Person( named: “Hobbes”)

In each case you run the init function. A new object is allocated, and the object’s name var is set to your specification.

Behind the scenes, the initializer increments the static population variable. To get the string stored in an object’s name, you simply use dot notation.

// You know this part....
print(“This object’s name is: \(calvin.name)” )  // extract the contents from the object.

But how do you get the value of the population variable? Do you ask the calvin object? Or do you ask the hobbes object?

It doesn’t make sense to ask the calvin object how many Person objects were created. A single person object should only contain data relating to that one instance that you created.

So to read the population var in code, you’ll need to supply the struct name. Example:

// Extract the value from the struct definition
let totalNumberOfPersonObjectsCreatedByUser = Person.population // struct name required

Because you defined population as a static, the compiler removes the population definition from the object when you create a new one. Your object only contains the name var, and the initializer function.

So what happens when you try to run the init function? In your example, the init tries to update a variable that doesn’t exist in the instance! This is the error you mentioned, and the reason you must supply the struct’s name when you access a static property.

Clear as Earl Grey tea?

2      

I started to realize that I knew everything you were saying and all I really needed was this:

So what happens when you try to run the init function? In your example, the init tries to update a variable that doesn’t exist in the instance! This is the error you mentioned, and the reason you must supply the struct’s name when you access a static property.

Thanks! 😅

This question came from taking one of Paul Hudson's tests (question 7), and I'm pretty sure that his statement when you get the question right is incorrect. It says, "Correct! Referencing a static property inside a regular method isn't allowed; this should use Person.population."

That first part cannot be right. You can access static properties without a problem inside non-static methods. I mean, you literally do just that after you correctly add back in the Person struct before .population. Any ideas on what he was trying to state?

1      

This may help from Apple's own documentation on the Swift language.

It starts with Instance Methods, and progresses to Type Methods, where the static keyword is introduced.

2      

Sure, the documentation is always the answer! But, that statement from Paul Hudson is incorrect, right? You can certainly access static properties inside regular non-static methods.

1      

@twoStraws notes

"Correct! Referencing a static property inside a regular method isn't allowed; this should use Person.population."

This might read better by saying

"Correct! Directly referencing a static property inside a regular method isn't allowed.
You must preface the static property with the struct's name like this: Person.population"

I am not sure his answer is wrong, but perhaps it could be clearer?

1      

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!

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.