swift - Returning protocol type -
i have protocol graphtype can have specific implementations:
protocol graphtype { var vertexcount: int {get} var edgecount: int {get} init(vertexcount: int) ... } then have function construct mst:
func primsmst(graph: graphtype) -> graphtype { let ret = graph.dynamictype(vertexcount: graph.vertexcount) return ret } there no direct compiler warning in code, compiler complains function:
while emitting ir sil function @_tf10swiftstuff8primsmstfps_9graphtype_ps0__ 'primsmst' @ /users/aeubanks/dropbox/programming/apps/swiftstuff/swiftstuff/mst.swift:9:1
command failed due signal: segmentation fault: 11
this shouldn't problem right? function takes in object implements graphtype , returns arbitrary graphtype happens same input. when replace graph.dynamictype specific implementation graphadjacencylist without changing return type compiles, prefer if return type same class inputted graph. auto-correct says ret of graphtype. way solve this?
use generic function. here's reduced version of code:
protocol graphtype { var vertexcount: int {get} init(vertexcount: int) } func primsmst<t:graphtype>(what:t) -> graphtype { let result = t(vertexcount:what.vertexcount) return result } let's try out. i'll define struct adopts graphtype:
struct st : graphtype { var vertexcount = 0 init(vertexcount:int) { self.vertexcount = vertexcount } } here go....
let st = st(vertexcount:25) let result = primsmst(st) a little logging / breakpointing show result want be.
Comments
Post a Comment