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)
}
}
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 )
}
}
1条答案
按热度按时间mkshixfv1#
下面是一个简单的例子。
注意,当你从一个泛型类派生子类时,你必须把子类也作为泛型,并且必须把子类中使用的泛型变量传递给超类。(在我们情况下是协议),请参阅类B中的初始化程序。初始化子类还要求在初始化为B时传递显式泛型类型()。这是我自己的实验。可以有更简单更简洁的方法来做这件事。
更新Swift 5.7
在Swift 5.7中,您可以使用
some
和any
来处理此问题,它们提供了更好的语法。