Associated type inference doesn't work in a situation that I assumed it would

Anyone have any knowledge about the code below and the possibility of it working in some future?

protocol A {
    associatedtype T
}
protocol B: A {
    var t: T { get }
}
struct X: B {
//    typealias T = Int // This line makes it compile, but I wish this type could be inferred.
    var t: Int {
        0
    }
}

This is a known issue, but it is possible to work around by adding an associated type to B:

protocol A {
  associatedtype T
}
protocol B: A {
  associatedtype T
  var t: T { get }
}
struct X: B {
  var t: Int { 0 }
}

However, if in the future A picks up additional requirements, you will have to repeat those requirements in B:

protocol A {
  associatedtype T
  var a: T { get }
}
protocol B: A {
  associatedtype T
  var a: T { get }
  var t: T { get }
}
struct X: B {
  var a: Int { 0 }
  var t: Int { 0 }
}

Otherwise Swift will erroneously allow the instance variables a and t to be of different types.

1 Like