Response to Ghost of Swift Bugs Future
/*: | |
# response to [__Ghost of Swift Bugs Future__ by ALEXANDROS SALAZAR](http://nomothetis.svbtle.com/the-ghost-of-swift-bugs-future) | |
*/ | |
protocol A { | |
func m1() -> String | |
} | |
extension A { | |
func m1() -> String { | |
return "hello" | |
} | |
func m2() -> String { | |
return "planet" | |
} | |
} | |
struct B : A { | |
func m1() -> String{ | |
return "greetings" | |
} | |
func m2() -> String { | |
return "earthling" | |
} | |
} | |
struct C : A { | |
func m2() -> String { | |
return "darkness, my old friend" | |
} | |
} | |
/*: | |
# first error | |
type inferences can't (arguably shouldn't) infer this as an array with Element type A | |
*/ | |
//let e = [B(), C()] | |
/*: | |
# second error | |
if the array has an Element type of Any, an incomprehensible error is shown caused by m1 and m2 not being visible to the compiler's static type checking | |
*/ | |
//let e2:[Any] = [B(), C()] | |
//print(e2.map{$0.m1()}) // ["greetings", "hello"] | |
//print(e2.map{$0.m2()}) // ["earthling", "darkness, my old friend"] | |
/*: | |
# array of A | |
an array of A shows that static dispatch is used for m2, calling the protocol extension method | |
*/ | |
let a:[A] = [B(), C()] | |
print(a.map{$0.m1()}) // ["greetings", "hello"] | |
print(a.map{$0.m2()}) // ["planet", "planet"] | |
/*: | |
# direct objects | |
calling the methods on values of the concrete types B and C shows static dispatch calling the implementations of those types | |
*/ | |
B().m1() // "greetings" | |
C().m1() // "hello" | |
B().m2() // "earthling" | |
C().m2() // "darkness, my old friend" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment