-1

I have a completion handler function with a string in return value.

func hardProcessingWithString(input: String, completion: (result: String) -> Void) {}

However, Xcode requires me to put _ before my return value name so I have to put _ before result

func hardProcessingWithString(input: String, completion: (_ result: String) -> Void) {}

and because of that, when I call my function, my return value doesn't have name but instead it shows this

hardProcessingWithString(input: String, completion: (String) -> Void)

Is there a way that instead of showing

completion: (String) -> Void)

I want it to show

completion: result -> Void)

so that I know exactly what return value means instead of the completion type. Thanks!

KevinVuD
  • 581
  • 2
  • 5
  • 25
  • This Swift feature has been discussed before in some post, remember it start from Swift 3.2, I find it really bad also, but there's no way to show param names for now. – Tj3n Jul 26 '18 at 02:49

3 Answers3

1

Since some version of Swift, closure types can't have parameter names. However, there is a workaround:

typealias Result = String

And now you can use Result as the closure type:

func f(completion: (Result) -> Void) { ... }

Many methods in Foundation also does this. For example TimeInterval is just an alias for Double, but naming it TimeInterval makes the purpose clearer.

Sweeper
  • 213,210
  • 22
  • 193
  • 313
1

You shouldn't add labels for closure definition. Just define it like this.

func hardProcessingWithString(input: String, completion: (String) -> Void) {}

When this function called, you should define the label.

hardProcessingWithString(input: "") { (result) in

}
Lumialxk
  • 6,239
  • 6
  • 24
  • 47
0

This is by design (though, to be sure, not everyone likes it). See

https://bugs.swift.org/browse/SR-2894

As Jordan Rose explains:

This is correct behavior. The argument labels are considered part of a function's name, not its type. A function value / closure has only a base name and no argument labels, so they cannot be specified.

matt
  • 515,959
  • 87
  • 875
  • 1,141