You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
* 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.
Copy file name to clipboardExpand all lines: docs/DynamicCasting.md
+11-6Lines changed: 11 additions & 6 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -407,9 +407,10 @@ S.self.svar // 2
407
407
```
408
408
409
409
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`
411
412
* 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)
413
414
414
415
### Note: "Self conforming" protocols
415
416
@@ -439,10 +440,14 @@ let b : MyGenericType(a)
439
440
As above, since `a` has type `P`, this code is instantiating `MyGenericType` with `T = P`, which is only valid if `P` conforms to `P`.
440
441
441
442
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.
0 commit comments