After reading an discussion about using Self
in protocol, I did an experiment (see code below). I thought the code would fail to compile because, from my understanding, for class B
to conform to Copyable
protocol, it should have init(_ instance: B)
, which I didn't define. But the code actually works.
I wonder why? Thanks for any explanation.
1 import Foundation
2 protocol Copyable: class {
3 init(_ instance: Self)
4 }
5 class A: Copyable {
6 var x: Int
7
8 init(x: Int) {
9 self.x = x
10 }
11
12 required init(_ instance: A) {
13 self.x = instance.x
14 }
15 }
16 class B: A {
17 var y: Int
18
19 init(x: Int, y: Int) {
20 self.y = y
21 super.init(x: x)
22 }
23
24 required init(_ instance: A) {
25 self.y = 1
26 super.init(instance)
27 }
28 }
29 var a = A(x:1)
30 var b = B(a)