简体   繁体   English

如何在 Swift 3 中记录函数闭包参数的参数?

[英]How do you document the parameters of a function's closure parameter in Swift 3?

In Xcode 8 beta and Swift 3, when you have a method that takes a closure as a parameter, for example:在 Xcode 8 beta 和 Swift 3 中,当您有一个将闭包作为参数的方法时,例如:

func foo(bar: (String) -> Void) {
    bar("Hello, world")
}

How do you document the parameters the closure takes?你如何记录闭包所采用的参数? For example, if I wrote this:例如,如果我这样写:

/// Calls bar with "Hello, world"
/// - parameter bar: A closure to call
func foo(bar: (String) -> Void) {
    bar("Hello, world")
}

Then the quick help looks like this:然后快速帮助看起来像这样:

foo(bar:) 快速帮助

I would like to know what the syntax is that will allow me to write some text to replace "No description."我想知道允许我写一些文本来替换“无描述”的语法是什么。 Many thanks!非常感谢!

As far as I know, you can only document the closure parameters if you label them:据我所知,如果你给它们贴上标签,你只能记录闭包参数:

/// Calls bar with "Hello, world"
/// - parameter bar: A closure to call
/// - parameter theString: A string to use
func foo(bar: (theString: String) -> Void) {
    bar(theString: "Hello, world")
}

This is less than ideal: it forces you to use an argument label when you call the closure, and if there are naming conflicts, there seems no way to distinguish between the two.这不太理想:它迫使您在调用闭包时使用参数标签,并且如果存在命名冲突,似乎无法区分两者。

Edit : As @Arnaud pointed out, you can use _ to prevent having to use the parameter label when calling the closure:编辑:正如@Arnaud 指出的那样,您可以使用_来防止在调用闭包时必须使用参数标签:

/// Calls bar with "Hello, world"
/// - parameter bar: A closure to call
/// - parameter theString: A string to use
func foo(bar: (_ theString: String) -> Void) {
    bar("Hello, world")
}

In fact, this is the only valid approach in Swift 3 because parameter labels are no longer part of the type system (see SE-0111 ).事实上,这是 Swift 3 中唯一有效的方法,因为参数标签不再是类型系统的一部分(参见SE-0111 )。

This seems to be broken for quite some time.这似乎打破了很长一段时间。 Here is an example with XCode 11.6, where you can see that :这是 XCode 11.6 的示例,您可以在其中看到:

1 ) the parameters are documented as explained in @Tim Vermeulen answer 1 ) 参数记录在@Tim Vermeulen 的回答中在此处输入图片说明

2 ) nevertheless, the "no description" table appears in the help pop-over window 2 ) 尽管如此,“无描述”表出现在帮助弹出窗口中在此处输入图片说明

3 ) BUT the text appears correctly in the quick help window 3 )但是文本在快速帮助窗口中正确显示在此处输入图片说明

I guess we need to wait (hope) for Apple to fix this.我想我们需要等待(希望)苹果来解决这个问题。

A slight improvement, though.不过略有改善。 Instead of writing "Parameter" at each line, use the following syntax :不要在每一行写“参数”,而是使用以下语法:

- Parameters:
  - name1: description
  - name2: description

(indentation seems to be important) (缩进似乎很重要)

Then you'll get然后你会得到在此处输入图片说明

But it doesn't work everywhere the function is called...但它在调用函数的任何地方都不起作用......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM