Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subclass another class with generic in Swift?

Tags:

generics

swift

My protocols and classes are:

protocol Named {

}

class A<T: Named> {

}

And now I want to create a class inherents from P:

class B: A {

}

But a compile error occupy, it says:

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

Please tell me how can I subclass another class with generic, thanks!

like image 328
migrant Avatar asked Jul 29 '14 06:07

migrant


1 Answers

When I see your code, it seems perfectly fine but I have no idea what you have been 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 you subclass from a generic class, you have to have the subclass as the generic as well, and the super class must be passed the same generic variable used in subclass. It also seems like explicit typecasting is necessary to denote the generics (protocol in our case), see initializer in class B. Initializing subclass also requires the explicit generic type to be passed while initializing as B(). This is my own experiment. There could be easy and more succinct ways to do this.

like image 123
Sandeep Avatar answered Oct 30 '22 09:10

Sandeep