1

I have a collection say Array that contains objects that implement this protocol

protocol Observer {
    func update(message: String)
}
let observers = [Observer]()
... 
// usually I use this loop to tell all observers 
for observer in observers {
    observer.update(message: "updated")
}

What I want here is to do something like that:

observers.executeForAll{$0.update(message:"updated")}

I know this exists in other programming languages, but can this be done in swift.

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
Khaled Annajar
  • 15,542
  • 5
  • 34
  • 45

1 Answers1

1

You can try

observers.forEach { $0.update(message: "updated") }
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
  • 3
    Why did you reopen the question? This is a duplicate. Your solution is identical to the one in https://stackoverflow.com/a/24446427/1187415 – Martin R Dec 20 '18 at 12:05
  • This should be the answer you wanted @KhaledAnnajar – Jonathan Dec 20 '18 at 12:21
  • 1
    @MartinR this isn't a duplicate because the question is actually really different – Jonathan Dec 20 '18 at 12:25
  • 1
    @MartinR this isn't a direct duplicate of the question even with another title , plus if you look for duplicates can you close for example delegate pattern questions which has dozens of similar answers daily and for sure you see them ? – Shehata Gamal Dec 20 '18 at 12:33
  • 1
    @MartinR I just could not find the question you are pointing to before creating my question. – Khaled Annajar Dec 20 '18 at 15:54