Generic protocol inside generic protocol in Swift 3 -


i want create interface (protocol) tree in swift. tree use interface (protocol) treenodes. these interfaces should generic. ideally want have this:

protocol treenodeinterface {     associatedtype t: elementinterface      var value: t { set }      // ... other methods  }  protocol treeinterface {     var rootnode: treenodeinterface<t>? { }      func clean()      // .. other methods }  class tree<t: elementinterface>: treeinterface {     var root: treenodeinterface<t>?      var rootnode: treenodeinterface<t>? {         {             return root         }     }      func clean() {      } } 

so example have class tree inherited treeinterface , can initialize tree type (int, string, customclass etc), each node have type value.

i managed object oriented programming, cannot protocol oriented programming

swift doesn't allow me this. can me here? thanks

i think you're trying protocols. biggest problem here cannot create variable protocol type if protocol has associated type (or self requirement). replacing these definitions generics, ended this:

protocol treenodeinterface {     associatedtype element: elementinterface      var value: element { set }      // ... other methods }  protocol treeinterface {     associatedtype node: treenodeinterface      var rootnode: node? { }      func clean()      // .. other methods }  class tree<t: treenodeinterface>: treeinterface {     typealias node = t     var rootnode: t?      init() {}      func clean() {      } } 

this compiles, have figure out how initialize it. next step make type conforms treenodeinterface:

struct treenode<t: elementinterface>: treenodeinterface {     typealias element = t     var value: t } 

this looks strikingly similar protocol, that's alright. let's initialize tree:

// assuming int conforms elementinterface let tree = tree<treenode<int>>() 

phew! lot of work, of consider unnecessary. need treenodeinterface , treeinterface? i'd argue don't. here's might if used concrete types instead:

struct treenode<t: elementinterface> {     var value: t }  class tree<t: elementinterface> {     var root: treenode<t>?      init() {}      func clean() {      } }  let tree = tree<int>() 

Comments

Popular posts from this blog

How to understand 2 main() functions after using uftrace to profile the C++ program? -

c# - Update a combobox from a presenter (MVP) -

How to put a lock and transaction on table using spring 4 or above using jdbcTemplate and annotations like @Transactional? -