outfoxx / swiftpoet

Kotlin and Java API for generating .swift source files.
Apache License 2.0
277 stars 26 forks source link

Support for optional closure/lambda parameters #72

Closed ema987 closed 1 year ago

ema987 commented 1 year ago

Hello there,

I want to use generate the following function where the closure parameter is optional:

func test(closure: ((Swift.String, Swift.Int) -> Swift.String)?) {}

I tried it modifying a bit the already existent test in FunctionSpecTests using makeOptional(),

val closureTypeName =
      FunctionTypeName.get(listOf(ParameterSpec.unnamed(STRING), ParameterSpec.unnamed(INT)), STRING)
        .makeOptional()

but what I get is

func test(closure: (Swift.String, Swift.Int -> Swift.String?) {}

Furthermore, I tried also wanting the STRING return type as optional, so I changed the code to

    val closureTypeName =
      FunctionTypeName.get(listOf(ParameterSpec.unnamed(STRING), ParameterSpec.unnamed(INT)), STRING.makeOptional())
        .makeOptional()

and what I get is

func test(closure: (Swift.String, Swift.Int) -> Swift.String??) {}

If I'm not mistakenly using makeOptional() and I didn't miss something, it seems to me there is no way to emit the closure parameter between () to be able to mark it as optional using ? and the issue is in ParameterizedTypeName which always emits "%T?" without taking care of the parenthesis.

Could you check my PR for a solution proposal?