如何在Swift中使用泛型子类化另一个类?

hlswsv35  于 2022-12-10  发布在  Swift
关注(0)|答案(1)|浏览(196)

我的协议和类是:

protocol Named {

}

class A<T: Named> {

}

现在我想从P中创建一个类inherents:

class B: A {

}

但是一个编译错误占据了,它说:
Reference to generic type 'A' requires arguments in <...>
请告诉我如何用泛型子类化另一个类,谢谢!

mkshixfv

mkshixfv1#

下面是一个简单的例子。

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: A<Person> {
  init(){
    let person = Person(firstName: "John", lastName: "Appleseed")
    person.fullName
    super.init(named: person)
  }
}

注意,当你从一个泛型类派生子类时,你必须把子类也作为泛型,并且必须把子类中使用的泛型变量传递给超类。(在我们情况下是协议),请参阅类B中的初始化程序。初始化子类还要求在初始化为B时传递显式泛型类型()。这是我自己的实验。可以有更简单更简洁的方法来做这件事。

更新Swift 5.7

在Swift 5.7中,您可以使用someany来处理此问题,它们提供了更好的语法。

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 {
  var named: any Named

  init(named: some Named) {
    self.named = named
  }
}



class B: A {

  init() {
    let person = Person(firstName: "John", lastName: "Appleseed")
    person.fullName
    super.init(named: person )
  }

}

相关问题