以下代码不起作用。 我来自Java世界,我不明白为什么只要指定类型别名就不能返回通用协议?
我尝试在UserDao中使用associatedType Element: User
,typealias Element = User
来专门化它,但是每次getTest()方法返回相同的错误时:
Protocol 'UserDao' can only be used as a generic constraint because it has Self or associated type requirements
迅速做到这一点的好方法是什么?
import Foundation
protocol HasId {
}
protocol BaseDao {
associatedtype Element: HasId
}
protocol UserDao: BaseDao {
// already tried these solutions...
// associatedType Element: User
// typealias Element = User
}
class User: HasId {}
class Test {
func getTest() -> UserDao? { // Error is on the return type
return nil
}
}
答案 0 :(得分:2)
error: protocol 'UserDao' can only be used as a generic constraint because it has Self or associated type requirements
编译器给您上面的错误。
您不能将具有关联类型的协议用作函数参数或返回类型,因为它需要知道要与该协议关联的类型别名。
如果您来自Java世界,这似乎很令人沮丧,但是解决方案是使用一个类来定义与您的类型相关联的类型别名。
protocol BaseDao {
associatedtype Element: HasId
}
class UserDao: BaseDao {
typealias Element = User
}
答案 1 :(得分:0)
将UserDao
更改为class
或struct
:
class UserDao: BaseDao {
typealias Element = User
}