Muh*_*Ali 5 generics protocols swift
在swift协议中使用泛型函数或与associatedType有什么区别?
protocol Repository {
associatedtype T
func add(data : T) -> Bool
}
Run Code Online (Sandbox Code Playgroud)
和
protocol Repository {
func add<T>(data : T) -> Bool
}
Run Code Online (Sandbox Code Playgroud)
定义的关联类型使符合协议的类成为强类型。这提供了编译时错误处理。
另一方面,泛型使符合协议的类更加灵活。
例如:
protocol AssociatedRepository {
associatedtype T
func add(data : T) -> Bool
}
protocol GenericRepository {
func add<T>(data : T) -> Bool
}
class A: GenericRepository {
func add<T>(data : T) -> Bool {
return true
}
}
class B: AssociatedRepository {
typealias T = UIViewController
func add(data : T) -> Bool {
return true
}
}
Run Code Online (Sandbox Code Playgroud)
class A可以将任何类放入add(data:)函数中,因此您需要确保该函数可以处理所有情况。
A().add(data: UIView())
A().add(data: UIViewController())
Run Code Online (Sandbox Code Playgroud)
两者都是有效的
但是对于类B,当您尝试放置除以下内容以外的任何内容时,都会出现编译时错误UIViewController
B().add(data: UIView()) // compile-time error here
B().add(data: UIViewController())
Run Code Online (Sandbox Code Playgroud)