Jason Chan Jason Chan - 4 months ago 169
iOS Question

How to change the value of a property of all the instances of a class?

I have a Student Class and a Uniform Class.
When an Student instance is created, the student will have a uniform with Green Color.

class Student{
var uniform = Uniform.uniformColor
}

class Uniform{
static var uniformColor = "Green"
{
didSet(newColor){
print("Change to \(newColor)")

}
}

}



let student1 = Student()
let student2 = Student()

print(student1)
print(student2)

Uniform.uniformColor = "Red"

print(Uniform.uniformColor)

print(student1.uniform)
//print Green
print(student2.uniform)
//print Green
let student3 = Student()
print(student3.uniform)
//print Red


How do I set the colour of the uniform of all the students, to Red at once?

Answer

If you always want a student to have the latest Uniform.uniformColor, then change uniform to a computed property:

class Student {
    var uniform: String { return Uniform.uniformColor }
}

Example:

let student1 = Student()
let student2 = Student()

print(student1.uniform)  // Green
print(student2.uniform)  // Green

Uniform.uniformColor = "Red"

print(student1.uniform)  // Red
print(student2.uniform)  // Red
Comments