【发布时间】:2018-12-28 10:02:15
【问题描述】:
以下代码不起作用。 我来自 Java 世界,我不明白为什么只要指定 typealias 就不能返回泛型协议?
我尝试在 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
swift 有什么好方法?
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
}
}
【问题讨论】:
-
错误解释得很清楚
Protocol 'UserDao' can only be used as a generic constraint because it has Self or associated type requirements。已经解释 - 请参考链接:stackoverflow.com/questions/27725803/… -
这是一篇很好的文章,可能会解决你的问题:medium.com/capital-one-tech/…