Method with generic constraint of generic classes not called

I agree that this can be unintuitive and a bit cumbersome to work with. If what you want to achieve in your actual use case is to let the implementation of bar() depend on Output you can attach it to the output type:

class MyTest<Output: P> {
  let myVar: Output

  init(myVar: Output) {
    self.myVar = myVar
  }

  func foo() {
    Output.bar(for: self)
  }
}

protocol P {
  static func bar<Output: P>(for myTest: MyTest<Output>)
}

extension P {
  static func bar<Output: P>(for myTest: MyTest<Output>) {
    print("'bar' without generic constraint")
  }
}

extension String: P {}
extension Int: P {
  static func bar<Output: P>(for myTest: MyTest<Output>) {
    print("'bar' constrained to 'Int' output")
  }
}


func test() {
  let myTest1 = MyTest(myVar: 5)
  myTest1.foo() // 'bar' constrained to 'Int' output

  let myTest2 = MyTest(myVar: "String")
  myTest2.foo() // 'bar' without generic constraint
}
test()
4 Likes