generics - Why doesn't this Swift code type-check? -


the following swift code:

class workflow<itemclass: hashable> {     var block: (itemclass -> int)?     init() {} }  protocol protocolx {     typealias itemclass     func foo(x: itemclass) -> int }  func test<y: protocolx, itemclass: hashable>(protx: y, x: itemclass) {     let workflow = workflow<itemclass>()     workflow.block = { (x: itemclass) in         return protx.foo(x)     } } 

fails compiler error:

cannot invoke 'foo' argument list of type '(itemclass)':  expected argument list of type '(self.itemclass)' 

in code snippet return protx.foo(x).

this may seem contrived example, it's reduced real-world problem i'm having.

if try following advice in error message, get:

'self' available in protocol or result of method in class;  did mean 'test'? 

how can type-check?

you have given compiler no reason believe workflow.itemclass same type protocolx.itemclass within function test(_:x:). if mean require itemclass type parameter test function same protocolx.itemclass within function, can tell compiler require it, this:

func test<y: protocolx, itemclass: hashable y.itemclass == itemclass>(protx: y, x: itemclass) {     let workflow = workflow<itemclass>()     workflow.block = { (x: itemclass) in         return protx.foo(x)     } } 

but can eliminate separate itemclass parameter entirely:

func test<y: protocolx y.itemclass: hashable>(protx: y, x: y.itemclass) {     let workflow = workflow<y.itemclass>()     workflow.block = { (x: y.itemclass) in         return protx.foo(x)     } } 

Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -