Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // note, P does not declare greet as requirement
- protocol P {}
- // ... but this does provide a "default" implementation
- extension P {
- func greet() {print("hello")}
- }
- // ... so if you have a class that overrides this
- class C : P {
- func greet() {print("hello from C")
- }
- }
- // but then use the protocol, rather than the class
- func greeter(_ obj: P) {
- obj.greet()
- }
- // then this will, confusingly IMHO, print "hello", not "hello from C"
- greeter(C())
- // ----
- // However, if we define a protocol with this as a requirement
- protocol Q {
- func greet()
- }
- // ... and provide a default implementation
- extension Q {
- func greet() {print("hello")}
- }
- // ... and then override this default implementation
- class D : Q {
- func greet() {print("hello from D")}
- }
- // ... now this Q will honor any overrides that the class may implement
- func anotherGreeter(_ obj: Q) {
- obj.greet()
- }
- // ... this will now print "hello from D", as you'd expect it to
- anotherGreeter(D())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement