1

I have this protocol

protocol BinaryTreeProtocol {
    associatedtype T
    var info: T { get set }
    var left: Self? {get set}
    var right: Self? {get set}
    func addItem(item: T)
}

And I can't complete its implementation.

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

    }
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571

1 Answers1

1

I think the problem you are facing has two elements:

  • the recursive reference to the same type as hinted by the compiler. Basically, you are using a struct,whose size should be known at compile time; adding a recursive reference to its type prevents this

  • you are using 'Self' in the protocol declaration, which may lead to cases where non-fully initialised instances are created (see: Protocol func returning Self); i.e you need to use final for implementation to make sure the Self instances are of specific class and thus fully initialised;

I've modified your code reflecting my comments:

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

   }
}

Hope this helps and enjoy Swift :)

Ivan S Ivanov
  • 532
  • 5
  • 10