How are subclasses of another class shared in Swift?

My protocols and classes:

protocol Named { } class A<T: Named> { } 

And now I want to create an inherent class from P:

 class B: A { } 

But a compilation error takes:

Reference to generic type 'A' requires arguments in <...>

Please tell me how I can subclass another class with a common one, thanks!

+6
source share
1 answer

When I see your code, it looks great, but I have no idea what you were doing inside the classes. Here is a simple example.

 protocol Named{ var firstName:String {get set} var lastName: String {get set} var fullName: String{ get } } class Person: Named{ var firstName: String var lastName: String var fullName: String{ return "\(firstName) \(lastName)" } init(firstName: String, lastName: String){ self.firstName = firstName self.lastName = lastName } } class A<T: Named>{ var named: T init(named: T){ self.named = named } } class B<M: Named>: A<M>{ init(){ let person = Person(firstName: "John", lastName: "Appleseed") person.fullName super.init(named: person as M) } } let b = B<Person>() b.named.fullName 

Note that when subclassing from a generic class, you must also have the subclass as generic, and the same generic variable used in the subclass must be passed to the superclass. It also seems that generic generics (the protocol in our case) require explicit type conversions, see Initializer in class B. Initializing a subclass also requires that an explicit generic type be passed during initialization as B (). This is my own experiment. There may be easier and more concise ways to do this.

+10
source

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


All Articles