Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Delegation example #1 for the Aya.io tutorial.
protocol ListensToEvents {
func anEventHappened(code: Int)
}
class ClassicPrinter: ListensToEvents {
func anEventHappened(code: Int) {
print("CODE: \(code)")
}
}
class FancyPrinter: ListensToEvents {
func anEventHappened(code: Int) {
print("\(NSDate()) - GENERATED CODE: \(code)")
}
}
class EventsGenerator {
var delegate: ListensToEvents?
var codes = [Int]()
func generateNewCode() {
codes.append(Int(arc4random_uniform(1_000_000)))
if let printer = delegate {
printer.anEventHappened(codes.last!)
} else {
// No delegate, the code stays secret...
}
}
}
let generator = EventsGenerator()
generator.generateNewCode()
generator.delegate = ClassicPrinter()
generator.generateNewCode()
generator.delegate = FancyPrinter()
generator.generateNewCode()
generator.delegate = nil
generator.generateNewCode()
print(generator.codes)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.