Skip to content

Instantly share code, notes, and snippets.

@slavapestov
Created April 19, 2017 03:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slavapestov/2bebfcca4de105e453b17c0ec4302518 to your computer and use it in GitHub Desktop.
Save slavapestov/2bebfcca4de105e453b17c0ec4302518 to your computer and use it in GitHub Desktop.
func foo<T>(_: T) {
print("Self = \(T.self)")
}
protocol P {
func requirement()
}
extension P {
func requirement() {
foo(self)
}
func extensionMethod() {
foo(self)
}
}
class Base : P {
func classMethod() {
print("- Class method calls requirement")
requirement()
print("- Class method calls extension method")
extensionMethod()
}
func classMethodReturnsSelf() -> Self {
print("- Class method returning Self calls requirement")
requirement()
print("- Class method returning Self calls extension method")
extensionMethod()
return self
}
}
class Derived : Base {}
let d = Derived()
print("\n== Non-Self-returning class methods\n")
print("Calling class method:")
d.classMethod()
print("\nCalling class method with upcast value:")
(d as Base).classMethod()
print("\n== Self-returning class methods\n")
print("Calling class method returning self:")
d.classMethodReturnsSelf()
print("\nCalling class method returning self with upcast value:")
(d as Base).classMethodReturnsSelf()
print("\n== Protocol requirement\n")
print("Calling requirement:")
d.requirement()
print("\nCalling requirement with upcast value:")
(d as Base).requirement()
print("\nCalling requirement with existential value:")
(d as P).requirement()
print("^----- !!!")
print("\n== Extension method\n")
print("Calling extension method:")
d.extensionMethod()
print("\nCalling extension method with upcast value:")
(d as Base).extensionMethod()
print("\nCalling extension method with existential value:")
(d as P).extensionMethod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment