File tree Expand file tree Collapse file tree 2 files changed +32
-0
lines changed Expand file tree Collapse file tree 2 files changed +32
-0
lines changed Original file line number Diff line number Diff line change @@ -1272,6 +1272,15 @@ id swift_dynamicCastObjCProtocolUnconditional(id object,
1272
1272
Protocol * const *protocols,
1273
1273
const char *filename,
1274
1274
unsigned line, unsigned column) {
1275
+ if (numProtocols == 0 ) {
1276
+ return object;
1277
+ }
1278
+ if (object_isClass (object)) {
1279
+ // ObjC classes never conform to protocols
1280
+ Class sourceType = object_getClass (object);
1281
+ swift_dynamicCastFailure (sourceType, class_getName (sourceType),
1282
+ protocols[0 ], protocol_getName (protocols[0 ]));
1283
+ }
1275
1284
for (size_t i = 0 ; i < numProtocols; ++i) {
1276
1285
if (![object conformsToProtocol: protocols[i]]) {
1277
1286
Class sourceType = object_getClass (object);
@@ -1293,6 +1302,10 @@ id swift_dynamicCastObjCProtocolConditional(id object,
1293
1302
return nil ;
1294
1303
}
1295
1304
}
1305
+ if (object_isClass (object)) {
1306
+ // ObjC classes never conform to protocols
1307
+ return nil ;
1308
+ }
1296
1309
for (size_t i = 0 ; i < numProtocols; ++i) {
1297
1310
if (![object conformsToProtocol: protocols[i]]) {
1298
1311
return nil ;
Original file line number Diff line number Diff line change @@ -1081,4 +1081,23 @@ CastsTests.test("type(of:) should look through __SwiftValue")
1081
1081
expectEqual ( t, " S " ) // Fails: currently says `__SwiftValue`
1082
1082
}
1083
1083
1084
+ #if _runtime(_ObjC)
1085
+ @objc protocol P106973771 {
1086
+ func sayHello( )
1087
+ }
1088
+ CastsTests . test ( " Class metatype values should not cast to Obj-C existentials " ) {
1089
+ class C106973771 : NSObject , P106973771 {
1090
+ func sayHello( ) { print ( " Hello " ) }
1091
+ }
1092
+ // A class instance clearly conforms to the protocol
1093
+ expectTrue ( C106973771 ( ) is any P106973771 )
1094
+ // But the metatype definitely does not
1095
+ expectFalse ( C106973771 . self is any P106973771 )
1096
+ // The cast should not succeed
1097
+ expectNil ( C106973771 . self as? any P106973771 )
1098
+ // The following will crash if the cast succeeds
1099
+ ( C106973771 . self as? any P106973771 ) ? . sayHello ( )
1100
+ }
1101
+ #endif
1102
+
1084
1103
runAllTests ( )
You can’t perform that action at this time.
0 commit comments