我有以下代码:
protocol User {
var photo: Int { get }
}
protocol Relationship {
associatedtype Member: User
var first: Member { get }
var second: Member { get }
}
protocol Friend: User {
var a: Int { get }
}
protocol Lover: User {
var b: String { get }
}
protocol Friendship: Relationship
where Member: Friend {
var c: String { get }
}
protocol Love: Relationship
where Member: Lover {
var d: String { get }
}
enum RelationshipRecord<F, L>: Relationship
where F: Friendship, L: Love {
case friendship(value: F)
case love(value: L)
typealias Member = User
var first: Member {
switch self {
case .friendship(let o): return o.first
case .love(let o): return o.first
}
}
var second: Member {
switch self {
case .friendship(let o): return o.second
case .love(let o): return o.second
}
}
}
由于编译,我出现以下错误:
错误:类型'RelationshipRecord'不符合协议 “关系”
enum RelationshipRecord<F, L>: Relationship
和注释:
注意:可能旨在匹配“ RelationshipRecord.Member”(又名 “用户”)不符合“用户”
typealias Member = User
,
注意:协议要求嵌套类型'Member';您要添加吗?
associatedtype Member:
经过问题调查后,我知道将User从协议更改为类可使代码可编译。
class User {
var photo: Int { return 0 }
}
但这不是我所需要的。
是否可以同时保存以下内容:1)用户为协议,2)示例中的体系结构?
如果不是,为什么?
答案 0 :(得分:1)
您可以通过以下方式将第3个通用参数引入您的enum
:
enum RelationshipRecord<F, L, U>: Relationship where F: Friendship, L: Love, F.Member == U, L.Member == U {
case frienship(value: F)
case love(value: L)
var first: U {
switch self {
case .frienship(let o): return o.first
case .love(let o): return o.first
}
}
var second: U {
switch self {
case .frienship(let o): return o.second
case .love(let o): return o.second
}
}
}