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)
According to the documentation Self in this case will be A since A is the one conforming to the protocol, B is only doing it indirectly as a subclass of A.
So when A conforms to Copyable
you are saying that A and all its subclasses must have an init(_ instance: A)
In a protocol declaration or a protocol member declaration, the Self type refers to the eventual type that conforms to the protocol.
You can actually test this by removing the required init(_ instance: A)
init and you will get an error even if you have an init(_ instance: B)
, so since A is the class conforming to the protocol you must have an init where the instance
argument is A
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments