Description
Previous ID | SR-302 |
Radar | None |
Original Reporter | nelsonaa (JIRA User) |
Type | Bug |
Environment
Swift 2.1
Additional Detail from JIRA
Votes | 2 |
Component/s | Compiler |
Labels | Bug |
Assignee | None |
Priority | Medium |
md5: 9cc2494212f9a6ffebd0d8c1a93b8862
relates to:
- SR-118 Protocol extensions cannot be overridden in subclasses
Issue Description:
Problem
Invoking protocol function in a conforming type instance when there are both declaration and default implementation of that function in the protocol:
protocol P {
func f()
}
extension P {
func f() {
print("P")
}
}
struct S: P {
func f() {
print("struct P")
}
}
let myS = S()
myS.f()
// output: struct P
(myS as P).f()
// output: struct P
However, when there is only default implementation of that function:
protocol P {
}
extension P {
func f() {
print("P")
}
}
struct S: P {
func f() {
print("struct P")
}
}
let myS = S()
myS.f()
// output: struct P
(myS as P).f()
// output: P
As you can see, the overriding behaviour is not consistent in the above two cases.
This can also cause ambiguous types if two protocols implement the same method, maybe that should be a different bug but here is a code example
protocol Protocol1 {
}
protocol Protocol2 {
}
extension Protocol1 {
func printSomething() -> String {
print("hi")
return "hi"
}
func printOther() -> String {
print("bye")
return "bye"
}
}
extension Protocol2 {
func printSomething() -> String {
print("bye")
return "bye"
}
}
struct Person : Protocol1, Protocol2 {
func printOther() -> String {
print("people")
return "people"
}
}
let someone : Protocol2 = Person()
someone.printSomething()
let person : Person = someone as! Person
person.printSomething() //error Ambiguous
one would think that with Swift's goals of safety this would be caught at the struct implementation and not leak implementation to the user of the object.
This blog post goes into the full details http://nomothetis.svbtle.com/the-ghost-of-swift-bugs-future
This seems very error prone.
Potential Solutions
1) not allow overloading calls that have a default protocol implementation
2) call the overloaded in all cases
3) keep current behavior but have some required keyword stating it won't always be called similar to override to at least inform the programmer that the behavior might not be what they expect.