In Swift, the following code compiles without issue.
protocol P1 {
associatedtype T = Int
}
protocol P2 {
typealias T = Int
}
To me, these appear to behave almost identically. The only difference I have noticed is that there are additional restrictions on when you can use P1
because it has an associated type. In particular, let x: P1
is an error while let x: P2
is fine.
What is the actual difference between these two protocols? Are they treated differently in compiled code? Lastly, is there ever an advantage to using P1
rather than P2
?
Edit for clarity:
I know the working difference between associated types and type aliases, so I am surprised that you are even allowed to give an associated type a fixed value. That seems to defeat the entire purpose of an associated type. I am wondering if there is any utility to giving an associated type a fixed value, and I am wondering if these two protocols are different once compiled.