1

To provide some context:

P stands for property. The purpose of the code is that values of different types should be handled by individual methods (e.g. serializeInt, serializeDouble etc.), something like method overloading but the type of the argument coming from a type parameter.

The code below actually works fine. It calls the specialized pr( _: Int) implementation and prints "int".

But if I change the declaration "func pr(_ t: Int)" to the commented out one "func pr(_ t: T)", then the generic version gets called.

Anyone has any pointers to where this behavior is specified or why it works like this?

  protocol P {
     associatedtype T
     // this will be 'specialized' for concrete types
     func pr(_ t: T)

     // the operation that should call different pr implementations depending on T
     func op(_ t: T)
  }

  extension P {
     func op(_ t: T) {
        pr(t)
     }
  }

  // fallback implementation
  extension P {
     func pr(_ t: T) {
        print("generic")
     }
  }

  // pr 'specialized' on Int
  extension P where T == Int {
     //   func pr(_ t: T) {
     func pr(_ t: Int) {
        print("int")
     }
  }


  struct Prop<T>: P {
  }

  // create an Int prop and do the op
  let p = Prop<Int>()

  p.op(1)
E. Vladov
  • 61
  • 1
  • 3
  • Run into same problem. Any solution? – Michael_mhr Jun 15 '19 at 09:42
  • Well my confusion came from not realizing that the T generic parameter and the associated type T are not the same thing. As for the specific problem I had, I ended defining another protocol "SettingsBacked" and making the standard types conform to it. – E. Vladov Jun 15 '19 at 12:51

1 Answers1

0

Don't see any weird behavior. If you uncomment this line – func pr(_ t: T) {

Here p.op(1) will call default method, because you haven't provided implementation for op method where T == Int. And default op call default pr that's why it prints "generic".

Bohdan Savych
  • 3,310
  • 4
  • 28
  • 47
  • I meant if the code becomes: `extension P where T == Int { func pr(_ t: T) { print("int") } }` then it stops being called – E. Vladov Aug 22 '18 at 08:13