Skip to content

Instantly share code, notes, and snippets.

@gspiers
Last active May 10, 2017 12:23
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 gspiers/c14c3f8f23a92f4ac2366fb1842b7a70 to your computer and use it in GitHub Desktop.
Save gspiers/c14c3f8f23a92f4ac2366fb1842b7a70 to your computer and use it in GitHub Desktop.
Swift throwing methods in protocols
//: Playground - noun: a place where people can play

class MyError: Error {}

protocol P {
    func throwingFunc() throws -> Int
    func nonThrowingFunc() -> Int
}

class A: P {
    func throwingFunc() -> Int {
        return 5
    }
    
    func nonThrowingFunc() -> Int {
        return 5
    }
}

class B: P {
    func throwingFunc() throws -> Int {
        throw MyError()
    }
    
    func nonThrowingFunc() throws -> Int {
        throw MyError()
    }
}
Swift Compiler Error Group
MyPlayground.playground:20:7: Type 'B' does not conform to protocol 'P'
MyPlayground.playground:7:10: Protocol requires function 'nonThrowingFunc()' with type '() -> Int'; do you want to add a stub?
MyPlayground.playground:25:10: Candidate throws, but protocol does not allow it
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment