Created
February 27, 2016 18:09
-
-
Save ericdke/aa1ce0a3d38bed3291e3 to your computer and use it in GitHub Desktop.
Delegation example #1 for the Aya.io tutorial.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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