【发布时间】:2018-04-22 14:23:27
【问题描述】:
我正在尝试学习 Swift 4 泛型并编写了一些无法编译的代码。我不明白为什么。代码如下:
protocol NodeType {
associatedtype T
associatedtype E
var parent: T {get set}
var children: [T] {get set}
var item: E {get set}
func getItem()->E
mutating func setItem(_ newItem: E)
func getParent()->T
mutating func setParent(_ theParent:T)
func getChild(at index:Int)->T
mutating func insertChild(at index:Int, child: T)
func find(_ node:T)->Int
}
protocol ItemType:Equatable {
associatedtype E
var payload: E {get set}
func matches(_ item:E)->Bool
}
struct Item<E:Equatable>: ItemType {
var payload: E
func matches(_ item: E) -> Bool {
return payload == item
}
}
struct Node<T:NodeType, E:ItemType>: NodeType {
var parent: T
var children: [T]
var item: E
func getItem()->E {
return item
}
func find(_ node: T) -> Int {
for aNode in children {
// ********************************************************************
// the following line fails: Value of type 'T.E' has no member 'matches'
if aNode.getItem().matches(node) {
}
}
}
mutating func setItem(_ newItem: E) {
item = newItem
}
func getParent()->T {
return parent
}
mutating func setParent(_ theParent:T) {
parent = theParent
}
func getChild(at index:Int)->T {
precondition(0..<children.count ~= index)
return children[index]
}
mutating func insertChild(at index:Int, child: T) {
precondition(0...children.count ~= index)
if index == children.count {
// append at end
children.insert(child, at: children.endIndex)
}
else {
children.insert(child, at: index)
}
}
}
我的理解是,aNode 的类型 T 被限制为 NodeType,而 aNode.getItem() 是类型 E,被限制为 ItemType,其中包含函数匹配项。谁能告诉我哪里出错了。
【问题讨论】:
标签: xcode generics swift4 swift-protocols