Pro1
Writing this
protocol Pro1 {
typealias Element
}
you are just telling that there will be a type named Element
.
Pro2
Adding this
protocol Pro2: Pro1 {
typealias Element = Self
}
you are telling to the compiler that Element
will be the same type of the type that is implementing Pro2
.
So yes, there is a relation between the Element
in Pro1
and Pro2
.
Adding methods to Pro1
Let's declare 2 methods that will use Element
in Pro1
protocol Pro1 {
typealias Element
func a() -> Element
func b(elm: Element)
}
Conforming to Pro1
Now a class conform to Pro1
will be like this.
class Foo: Pro1 {
func a() -> String {
return ""
}
func b(elm: String) {
}
}
As you can see we are forced by the compiler to set the return type of a
and the param of b
to be of the same type.
Conforming to Pro2
Now let's try to conform another class to Pro2. Again Pro1
will force us to declare methods a
and b
where the return type of a is equals to the param of b
.
Furthermore Pro2
will force us to set this type equals to the type of the current type Boo
.
So the previous class will to conform to Pro2
because String
is different from Foo
class Foo: Pro2 {
func a() -> String { // <- compiler error
return ""
}
func b(elm: String) { // <- compiler error
}
}
But if we declare a new class and replace Element
with Boo
it will work because the constraints of both protocols are satisfied.
class Boo: Pro2 {
func a() -> Boo {
return Boo()
}
func b(elm: Boo) {
}
}