Swift Generic Unknown member with protocol extension

If I have the following code:

protocol ObjectType { var title: String { get set } } extension ObjectType { var objectTypeString: String { let mirror = Mirror(reflecting: self) return "\(mirror.subjectType)" } } class Object: ObjectType { var title = "" } class SomeOtherClass { private func someFunc<T: Object>(object: T) { print(object.objectTypeString) } } 

where Object corresponds to ObjectType , you can expect that you will be able to access objectTypeString on any ObjectInstance . But the compiler says that Type T has no member objectTypeString when this member is accessed by some common type that inherits from Object , as shown in the code above. When a function is not generic and simply passes into the Object parameter, there is no problem. So, why should the parameter be shared, so I can’t access the protocol member that the corresponding class should have access to?

I came across this question here , but I'm not interested in workarounds, I just would like to understand that this applies to the general system, which makes my example not work. (A simple workaround is <T: ObjectType> )

+5
source share
1 answer

Perhaps I am mistaken, or I did not understand your question completely, but I think that you may miss the beginning of the "object".

your wish code can be given below:

  protocol ObjectType { var title: String { get set } } extension ObjectType { var objectTypeString: String { let mirror = Mirror(reflecting: self) return "\(mirror.subjectType)" } } class Object: ObjectType { var title = "" } class SomeOtherClass { private func someFunc<T: Object>(object: T) { let object = Object() print(object.objectTypeString) } } 

but the fact is that even if we do not initiate an object, autocomplete returns a TypeString! that I don’t understand, and, as you said, maybe where the error occurs!

hope this helps <3

0
source

Source: https://habr.com/ru/post/1236517/


All Articles