On Xcode13beta3, BigSur 11.5:
protocol MyProtocol {
associatedtype T: SignedNumeric & Comparable
var prop: T { get }
func myMax(x: T, y: T) -> T
func myAbs(x: T) -> T
}
struct MyStruct: MyProtocol {
var prop: Int
func myMax(x: T, y: T) -> T { x < y ? y : x }
func myAbs(x: T) -> T { x < 0 ? -x : x }
}
for myAbs(x:)
Xcode first complains of the return T
, "Reference to invalid associated type 'T' of type 'MyStruct'". If I change the return T
to Int
and cast the return value to Int
, then it makes the same complain about the parameter type T
.
Two workarounds:
- Change both
T
s inmyAbs(x:)
toInt
:
struct MyStruct: MyProtocol {
var prop: Int
func myMax(x: T, y: T) -> T { x < y ? y : x }
func myAbs(x: Int) -> Int { x < 0 ? -x : x }
}
or
- add
typealias T = Int
inMyStruct
:
struct MyStruct: MyProtocol {
typealias T = Int
var prop: T
func myMax(x: T, y: T) -> T { x < y ? y : x }
func myAbs(x: T) -> T { x < 0 ? -x : x }
}
My question is whether it is expected behavior that the two T
s in myAbs(x:)
cannot be inferred or am I doing something wrong?
Also, if I swap the ordering of myAbs(x:)
and myMax(x:y:)
in MyStruct
, Xcode happily accepts myAbs(x:)
and complains about the T
s in myMax(x:y:)
instead.
Of the five threads this topic is similar to, three asked about why an associatedtype
inference succeeded, one was a pitch to remove associatedtype
inference, only one asked about associatedtype
not inferred. My case seems to be much simpler than the one reported in the last thread.
Thanks.