Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throwing an exception from an inherited function without throws

I'm trying to do the following:

protocol X{
    func foo()
}
enum XError{
    case BAR
}
class Y:X{
    func foo(){
        throw XError.BAR
    }
}

I can't add a throws declaration to the protocol and it complains that

the error is not handled because the enclosing function is not declared 'throws'.

How can I achieve this?

like image 870
Leonardo Marques Avatar asked Feb 28 '16 13:02

Leonardo Marques


1 Answers

You need to explicitly add throw in the signature of any function that throws.

So

func foo() throws {
    throw XError.BAR
}

This also applies to the protocol definition.

protocol X {
    func foo() throws
}

Errors in Swift should conform to the Error protocol.

enum XError: Error {
    case BAR
}
like image 68
Hugo Tunius Avatar answered Oct 22 '22 09:10

Hugo Tunius