如何在 iOS swift 中正确记录带有完成处理程序的方法

How can I properly document a method with a completion handler in iOS swift

我正在记录我公司 iOS 应用程序的代码,现在我已经转向具有完成处理程序的方法。是否有用于记录完成处理程序的特定方法,或者我应该将其作为参数的一部分?

例如:

/**
Description
- Parameters:
     - parameter1: description
     - parameter2: description
     - completion: description
*/

这是正确的方法还是有其他更好的方法?或者它应该在文档的 "Returns" 部分?

谢谢

尝试使用 VVDocumenter-Xcode 工具,它会自动将您的参数和 return 提取到文档中,如 javadoc 样式。

最好的方法是为您的完成处理程序创建一个 typealias。您可以更好地重用它,并且您的代码对用户来说更清晰。

另一方面,您可以像以前一样创建关于此的完整文档。

typealias closureType = (parameterTypes) -> (returnType)

/**
Sends an API request to 4sq for venues around a given location with an optional text search

:param: location    A CLLocation for the user's current location
:param: query       An optional search query
:param: completion  A closure which is called with venues, an array of FoursquareVenue objects

:returns: No return value
*/
func requestVenues(location: CLLocation, query: String?, completion: (venues: [FoursquareVenue]?) -> Void) { … }

取自https://thatthinginswift.com/documentation-and-quick-help/

Swift 评论语法目前(截至 2017 年 1 月)似乎不直接支持它。有一个未解决的问题,我鼓励您对 it/fix 投票 :) https://bugs.swift.org/browse/SR-874


但是,块类型可以单独定义:

/**
 - parameters:
    - error: See RequestError
    - image: Available if error is nil
*/
typealias RequestHandler = (_ error:RequestError?, _ image:UIImage?)->()

/** Requests a remote UIImage
 - parameter url: where to look for the image
 - parameter callback: invoked when request failed or completed
*/
func requstFrom(url: URL, callback:RequestHandler) { /* ... */ }

...这将允许看起来有点 not-terrible 的文档:

由于之前接受的答案无法在Swift 3下编译(函数类型不能有参数标签。)我想添加一个更新的答案:

/**
Find User ID from Request
- Parameter from: The request containing relevant information.
- Parameter completionHandler: The callback called after retrieval.
- Parameter userId: The retrieved user id.
*/
static func extractUserId(from: RouterRequest, completionHandler: (_ userId: String) -> Void)

结果

我觉得不错!