ios - Swift Collection Of Objects Conforming To Protocol With Associatedtype -


i have question (maybe regarding type erasure). imagine following scenario:

public protocol dataitem {      associatedtype t     var action: ((_ item: t) -> void)? {get} }  struct useritem: dataitem {      typealias t = useritem      // custom properties     let name: string      // protocol: dataitem     let action: ((t) -> void)? }  struct driveritem: dataitem {      typealias t = driveritem      // custom properties     let licensenumber: string      // protocol: dataitem     let action: ((t) -> void)? }  let items = [     useritem(name: "dexter", action: { (item) in print(item.name)}),     driveritem(licensenumber: "1234567890", action: { (item) in print(item.licensenumber)}) ]  items.foreach {     $0.action?($0) } 

i have dataitem abstract data item uitableviewcell , has action property should called when cell selected. question how can create array of dataitem objects, select item list (or iterate on it) , call respective action, print name of useritem , license number of driveritem. implementation above compiler complains following message items list can of type [any]...

heterogeneous collection literal inferred '[any]'; add explicit type annotation if intentional

that way cannot call action declared in protocol dataitem. tried wrap head around type erasures couldn't understand yet...

would happy if comes solution...

the error asks add type items:

let items: array<any> = [     useritem(name: "dexter", action: { (item) in print(item.name)}),     driveritem(licensenumber: "1234567890", action: { (item) in print(item.licensenumber)}) ] 

not sure if won't lead more errors because not sure if can call completion block while creating array.


edit

i think trying call when variable called. way use get typed didnt complete, so:

var licensenumber: string {     {         print("dosomething!")         return self.licensenumber     } } 

the array become like:

let items: array<any> = [     useritem(name: "dexter"),     driveritem(licensenumber: "1234567890") ] 

Comments

Popular posts from this blog

python - Selenium remoteWebDriver (& SauceLabs) Firefox moseMoveTo action exception -

html - How to custom Bootstrap grid height? -

transpose - Maple isnt executing function but prints function term -