Swift Protocol inheriting Protocol method with same name

Viewed 114

While reading swift forum about exceptions I found interesting issue. One of the examples about exceptions was something like this:

protocol Base {
    func foo() throws -> Int
}

protocol Refined: Base {
    func foo() -> Int
}

struct Test: Refined {
    func foo() -> Int {
        0
    }
}

It's interesting, I thought it was typo that it would not compile, but it does. I am not sure how this does work behind the scenes. I mean when protocol adopts another protocol it adopts also its requirements. But in this case declaring same method without throws somehow satisfies also first protocol Base.

At the very least I expected Test to need to have 2 implementations of foo. What am I missing here?

1 Answers

This is because a non-throwing function is by definition a sub-type of a throwing function

From the Swift Programming Language book

The throws keyword is part of a function’s type, and nonthrowing functions are subtypes of throwing functions. As a result, you can use a nonthrowing function in the same places as a throwing one.

But you can't do it the other way around so the below code will generate an error

protocol Base {
    func foo()  -> Int
}

protocol Refined: Base {
    func foo() throws -> Int //error: Cannot override non-throwing method with throwing method
}

Also note that this is not only for protocols, if you remove the func declaration from Refined you can still implement the function in Test as non throwing.

Related