简体   繁体   中英

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?

You could try to create an array of students, add each student to it. Next iterate with for-loop over all students and assign a Red color to Uniform.

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

Why not declare the color of Uniform as instance property and create a default initializer which always creates an Uniform with red color in the Student class?

class Student 
{  
  let uniform : Uniform

  init() {
    self.uniform = Uniform(color:"Red")
  }
}

class Uniform
{
  var color = "Green" {
    didSet(newColor){
      print("Change to \(newColor)")
    }
  }

  init(color : String) {
    self.color = color
  }
}

let student = Student()
print(student.uniform.color) // "Red"
var students = [Student]()
students.append(student1)
students.append(student2)
for student in students {
    student.uniform.uniformColor = "Red"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM