我有这个协议
protocol BinaryTreeProtocol {
associatedtype T
var info: T { get set }
var left: Self? {get set}
var right: Self? {get set}
func addItem(item: T)
}
我无法完成其实施。
struct BinaryTreeImplementation: BinaryTreeProtocol {
typealias T = Int
var info: Int
var left: BinaryTreeImplementation? // There is an error here.
var right: BinaryTreeImplementation? // how can I sort it?
func addItem(item: Int) {
}
}
我认为你面临的问题有两个要素:
struct
,它的大小应该在编译时知道;添加对其类型的递归引用可以防止这种情况final
来实现,以确保Self
实例具有特定的类,从而完全初始化;我修改了你的代码反映了我的意见:
protocol BinaryTreeProtocol {
associatedtype T
var info: T { get set }
var left: Self? {get set}
var right: Self? {get set}
func addItem(item: T)
}
final class BinaryTreeImplementation: BinaryTreeProtocol {
typealias T = Int
var info: Int = 0
var left: BinaryTreeImplementation?
var right: BinaryTreeImplementation?
func addItem(item: Int) {
}
}
希望这有助于享受Swift :)