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?