作者:金玉的海角_745 | 来源:互联网 | 2022-12-01 10:45
1> Taras Cherny..:
定义的关联类型使符合协议的类成为强类型。这提供了编译时错误处理。
另一方面,泛型使符合协议的类更加灵活。
例如:
protocol AssociatedRepository {
associatedtype T
func add(data : T) -> Bool
}
protocol GenericRepository {
func add(data : T) -> Bool
}
class A: GenericRepository {
func add(data : T) -> Bool {
return true
}
}
class B: AssociatedRepository {
typealias T = UIViewController
func add(data : T) -> Bool {
return true
}
}
class A
可以将任何类放入add(data:)
函数中,因此您需要确保该函数可以处理所有情况。
A().add(data: UIView())
A().add(data: UIViewController())
两者都是有效的
但是对于类B
,当您尝试放置除以下内容以外的任何内容时,都会出现编译时错误UIViewController
B().add(data: UIView()) // compile-time error here
B().add(data: UIViewController())