Last active
August 29, 2015 14:23
-
-
Save georgymh/e1f53f60c766456a235a to your computer and use it in GitHub Desktop.
Protocol and Delegates Playground
This file contains hidden or 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
| //: Playground - noun: a place where people can play | |
| import UIKit | |
| import Foundation | |
| @objc protocol Speaker { | |
| func Speak() | |
| optional func TellJoke() | |
| } | |
| class Vicki : Speaker { | |
| @objc func Speak() { | |
| println("Hello, I am Vicki!") | |
| } | |
| } | |
| // NOTE: When using @objc (for optional functions), the class | |
| // that conforms to the protocol should also have @objc preceeding | |
| // 'class', or preceeding every function from the protocol | |
| // (the first one is better). | |
| @objc class Ray : Speaker { | |
| func Speak() { | |
| println("Yo, I am Ray!") | |
| } | |
| func TellJoke() { | |
| println("Q: Whats the object-oriented way to become wealthy?") | |
| } | |
| func WriteTutorial() { | |
| println("I'm on it!") | |
| } | |
| } | |
| class Animal { } | |
| class Dog : Animal, Speaker { | |
| @objc func Speak() { | |
| println("Woof!") | |
| } | |
| } | |
| //var speaker : Speaker | |
| //speaker = Ray() | |
| //speaker.Speak() | |
| // | |
| //(speaker as! Ray).WriteTutorial() | |
| //speaker = Vicki() | |
| //speaker.Speak() | |
| // | |
| //speaker.TellJoke?() | |
| //speaker = Dog() | |
| //speaker.TellJoke?() | |
| protocol DateSimulatorDelegate { | |
| func dateSimulatorDidStart(sim: DateSimulator, a: Speaker, b : Speaker) | |
| func dateSimulatorDidEnd(sim: DateSimulator, a: Speaker, b : Speaker) | |
| } | |
| class LoggingDateSimulator : DateSimulatorDelegate { | |
| func dateSimulatorDidStart(sim: DateSimulator, a: Speaker, b: Speaker) { | |
| println("##### Date started! #####") | |
| } | |
| func dateSimulatorDidEnd(sim: DateSimulator, a: Speaker, b: Speaker) { | |
| println("##### Date ended! #####") | |
| } | |
| } | |
| class DateSimulator { | |
| let a : Speaker | |
| let b : Speaker | |
| var delegate : DateSimulatorDelegate? | |
| init(a : Speaker, b : Speaker) { | |
| self.a = a | |
| self.b = b | |
| } | |
| func simulate() { | |
| delegate?.dateSimulatorDidStart(self, a: a, b: b) | |
| println("Off to dinner...") | |
| a.Speak() | |
| b.Speak() | |
| println("Walking back home") | |
| a.TellJoke?() | |
| b.TellJoke?() | |
| delegate?.dateSimulatorDidEnd(self, a: a, b: b) | |
| } | |
| } | |
| let sim = DateSimulator(a: Vicki(), b: Ray()) | |
| sim.delegate = LoggingDateSimulator() | |
| sim.simulate() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment