|
Is there any reason why the name of the struct is actually needed when I'm accessing a static property? This causes an error:
This does not cause an error:
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! :) |
|
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. |
|
Joe is thinking about static vars
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
Now create two new
In each case you run the Behind the scenes, the initializer increments the
But how do you get the value of the It doesn’t make sense to ask the So to read the
Because you defined So what happens when you try to run the Clear as Earl Grey tea? |
|
I started to realize that I knew everything you were saying and all I really needed was this:
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 |
|
This may help from Apple's own documentation on the Swift language. It starts with Instance Methods, and progresses to Type Methods, where the |
|
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. |
|
@twoStraws notes
This might read better by saying
I am not sure his answer is wrong, but perhaps it could be clearer? |
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.
Sponsor Hacking with Swift and reach the world's largest Swift community!
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.
Link copied to your pasteboard.