【问题标题】:How to replace self on its implementation如何在其实现中替换 self
【发布时间】:2019-03-09 22:57:27
【问题描述】:

我有这个协议

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) {

    }
}

【问题讨论】:

  • 那么你不能拥有一个包含自身的属性
  • @LeoDabus 即使是可选的?
  • 没什么区别
  • 使用类而不是结构。

标签: swift generics swift-protocols type-alias associated-types


【解决方案1】:

我认为您面临的问题有两个要素:

  • 对编译器提示的同一类型的递归引用。基本上,您使用的是struct,其大小应在编译时知道;添加对其类型的递归引用可以防止这种情况发生

  • 您在协议声明中使用了“Self”,这可能会导致创建未完全初始化的实例(请参阅:Protocol func returning Self);即您需要使用final 进行实施,以确保Self 实例属于特定类并因此完全初始化;

我已经修改了反映我的 cmets 的代码:

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 :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-31
    • 2017-05-22
    • 2021-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多