Skip to content

Commit c98d895

Browse files
authored
Expanded discussion of protocol types (swiftlang#33621)
* AnyObject behaves as if every class type implicitly conformed to it as a protocol. * Protocols "inherit" from other protocols, and this has implications for casting to existential metatypes I also moved the Any self-conformance invariant to the self-conformance subsection and added a couple of explanatory sentences.
1 parent f588f2f commit c98d895

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed

docs/DynamicCasting.md

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -407,9 +407,10 @@ S.self.svar // 2
407407
```
408408

409409
Invariants
410-
* If `T` conforms to `P` and `t` is an instance of `T`, then `t is P`, and `T.self is P.Type`
410+
* If `T` conforms to `P` and `t` is an instance of `T`, then `t is P` and `T.self is P.Type`
411+
* If `P` is a sub-protocol of `P1` and `T` is any type, then `T.self is P.Type` implies that `T.self is P1.Type`
411412
* Since every type `T` conforms to `Any`, `T.self is Any.Type` is always true
412-
* `Any` self-conforms: `Any.self is Any.Type == true`
413+
* Since every class type `C` conforms to `AnyObject`, `C.self is AnyObject.Type` is always true (this includes Objective-C class types)
413414

414415
### Note: "Self conforming" protocols
415416

@@ -439,10 +440,14 @@ let b : MyGenericType(a)
439440
As above, since `a` has type `P`, this code is instantiating `MyGenericType` with `T = P`, which is only valid if `P` conforms to `P`.
440441

441442
Note that any protocol that specifies static methods, static properties, associated types, or initializers cannot possibly be self-conforming.
442-
As of Swift 5.3, there are only three kinds of self-conforming protocols:
443-
* `Any` must be self-conforming since every `T.self` is an instance of `Any.Type`
444-
* `Error` is a self-conforming protocol
445-
* Objective-C protocols that have no static requirements are self-conforming
443+
As of Swift 5.3, the only self-conforming protocols are `Any`, `Error`, and Objective-C protocols that have no static requirements.
444+
445+
Invariants
446+
* `Any` self-conforms: `Any.self is Any.Type == true`
447+
* `Error` self-conforms: `Error.self is Error.Type == true`
448+
* If `P` self-conforms and is a sub-protocol of `P1`, then `P.self is P1.Type == true`
449+
450+
For example, the last invariant here implies that for any Objective-C protocol `OP` that has no static requirements, `OP.self is AnyObject.Type`. This follows from the fact that `OP` self-conforms and that every Objective-C protocol has `AnyObject` as an implicit parent protocol.
446451

447452
## CoreFoundation types
448453

0 commit comments

Comments
 (0)