How to have a let property type be some other property type

I have a slew of functions that I want to change, each has a different type of block passed to it:

func foo(block _block: ) {

and for good reason I want to use a let property exist of the same type:

func foo(block _block: ) {
let block: type(of: _block) // doesn't work
let block: _block.self // doesn't work

Is there some way for me to accomplish this?

(BTW: I understand WHY the above techniques fail).

I think you can use a typealias:

typealias BlockType = () -> Int
func foo(block _block: BlockType)
let block: BlockType

You can have a typealias for each block type.

1 Like

There are already typealiases for each block, 30 or 40. I was hoping to avoid cut/paste - the boilerplate I have now would drop in easily if I could just type the let property. I posted this to see if I could avoid that.

Thank you for responding!

For large block, it's not ideal to type out the type in any form (though typealias is probably slightly better). What I ended up doing is to move let as close to the assignment as possible, and let the type inference do the thing. It's not always feasible ofc.

The idea is to define the block up top, but not set it:

let foo: SomeBlock

then later, the compiler generates error if foo is used before its set.

Yea, I've since abandon ISO C90 style declaration since it doesn't play well with type inference (in terms of convenience) and you'd get error on both use before declare and use before assign so not much is lost. The place I declare-without-assign is when the assignment can be different on different control path (if vs else) and when I don't want to expose temporary variables used to compute said variables. Anyhow, it's understandably style preference.

1 Like