Created
November 29, 2016 15:25
-
-
Save preble/9b4552c5ddbd1321ef95536d05840970 to your computer and use it in GitHub Desktop.
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 Protocol { | |
func methodInProtocol() -> String | |
} | |
extension Protocol { | |
func methodInProtocol() -> String { | |
return "Protocol" | |
} | |
func methodOnExtension() -> String { | |
return "Protocol" | |
} | |
} | |
struct Implementer: Protocol { | |
func methodInProtocol() -> String { | |
return "Implementer" | |
} | |
func methodOnExtension() -> String { | |
return "Implementer" | |
} | |
} | |
struct Underimplementer: Protocol { | |
// does not implement or override anything in Protocol | |
} | |
// Calling a method declared in the protocol and implemented in a protocol extension: | |
// Using actual type, method on Implementer is called, falling back to protocol extension method: | |
Implementer().methodInProtocol() // "Implementer" | |
Underimplementer().methodInProtocol() // "Protocol" | |
// Using the protocol type, same behavior as above _because the method is in the protocol_: | |
(Implementer() as Protocol).methodInProtocol() // "Implementer" | |
(Underimplementer() as Protocol).methodInProtocol() // "Protocol" | |
// Calling a method _not_ in the protocol, but on the extension, | |
// when called on the type, the method on the extension is the fallback: | |
Implementer().methodOnExtension() // "Implementer" | |
Underimplementer().methodOnExtension() // "Protocol" | |
// Because the method is not declared in the protocol, calling it upon the protocol calls the extension implementation: | |
(Implementer() as Protocol).methodOnExtension() // "Protocol" | |
(Underimplementer() as Protocol).methodOnExtension() // "Protocol" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment