Implementing a protocol with default implementations


(Daniel Eggert) #1

Optional protocols are implemented with

  1> protocol P {
  2. func bar()
  3. }
  4. extension P {
  5. func bar() {
  6. // do nothing
  7. }
  8. }

but all bets are off when I'm using this like so

  9> struct S {}
10. extension S : P {
11. func baz() {
12. print("Hello")
13. }
14. }
15.
16. let s = S()
s: S = {}
17> s.bar()
18>

This will not print anything, and the compiler will not tell me that I misspelled "bar" as "baz".

It would be extremely helpful to have a keyboard along the lines of "this is supposed to implement something in a protocol" -- which would give a warning (error?) if it doesn't.

I know there've been some discussions this, but particularly with complex protocol methods (take a look at NSURLSessionDelegate and friends), this is extremely tricky to get right, and the compiler does nothing to help me as a developer.

Take a look at this signature

func urlSession(session: NSURLSession, task: NSURLSessionTask, didReceive challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)

If I mistype that as

func urlSession(NSURLSession, task: NSURLSessionTask, didReceive challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)

or

func urlSession(session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)

it's very painful to track down why things don't work -> developers will be sad.

/Daniel