简体   繁体   中英

Swift: notify delegate in didSet?

I need some help on the best practice of notifying delegate in Swift, I have a ScoreStats model which has a list of Student , each Student has a score and the model provides average score for all the Student it refers to:

class ScoreStats {

  private(set) var averageScore: Double = 0

  var student: [Student]? {
    if let students = students {
      // calculate `averageScore`
    }
    // notify delegate
    self.delegate.averageScoreUpdated()
  }
}

My question is, coming from Objective C where people usually have a method like:

- (void)updateStudents:(NSArray<Student *> *)students {
  self.students = students;
  // calculate `averageScore`
  [self.delegate averageScoreUpdated];
}

From a language specific point of view, I can achieve the same purpose using didSet but is there any problem in other terms? For example, exposing the students property in Swift means different places can all modify it and the delegate would be notified, also it's not clear to the coder that setting students property would trigger a delegate notification for averageScore , whereas having a dedicate method in ObjC makes it more clear.

Opinions?

Your question is not really language specific. You need to decide when a delegate should be called. In your Objective-C code you added an updateStudents method. But for some reason you are taking a completely different approach in your Swift code. Why?

In either language you can either choose to make the students property fully public, fully private, or publicly read-only and privately settable. Of course Swift adds other levels of visibility but that's irrelevant to this discussion.

In either language you can choose to call the delegate in an additional method (like updateStudents ) or in the property's setter (again, Swift adds finer options for this but that's not important here).

So the basis of your question is flawed. It's not language specific. First decide when you want the delegate to be called. Is it anytime the students property is updated or is it when some other method is called?

If you want your Swift code to work just like your Objective-C code (with the same semantics), you do not want to call the delegate in the didSet of the property. You want to add the updateStudents method. And be sure you make the students property have the same visibility in both languages.

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