在Objective C中,我可以使用#pragma mark来标记符号导航器中的代码片段。由于这是一个C预处理器命令,所以在Swift中不可用。在Swift中有替代品吗,或者我必须使用丑陋的评论吗?


当前回答

//# MARK: - Spinner Class Methods

在冒号和描述之间添加一行,以插入分隔线。这有助于更好地组织代码。上面的代码和截图使用了包含一行的MARK注释。

//#标记:-文本方法(LINE) //#标记:文本方法(NO LINE)

这只适用于MARK注释。

其他回答

Xcode官方文档

苹果目前的官方文档部分为可见性注释代码引入了三个注释:TODO:, FIXME:和MARK:。

最新的Xcode版本(v14.2)支持另外两个注释(虽然没有出现在官方文档中):!!:和??

注意:! !:和??:被某些Xcode版本(如v10.0)不支持,原因未知。

示例截图1 - Xcode 14.2 + macOS 13.1 (Ventura)

示例截图2 - Xcode 10.1 + macOS 10.14.3 (Mojave)

在Objective-C代码中,Xcode检测像// MARK: - foo这样的注释,它比#pragma更可移植。但这些似乎也没有被采纳(目前?)

编辑:在Xcode 6 beta 4中修复。

苹果在最新版本的“构建可可应用程序”中表示,

Swift编译器不包括预处理器。相反,它需要 编译时属性、构建配置和 语言特性来完成相同的功能。对于这个 原因是,在Swift中不导入预处理器指令。

#字符似乎仍然是你处理各种构建配置和类似事情的方式,但看起来他们试图减少你对大多数预处理的需求,并将你转发到其他语言特性。也许这是为了帮助Playgrounds和REPL的操作尽可能接近完全编译的代码。

Use

// MARK: SectionName

or

// MARK: - SectionName

这将在pragma标记上面加一行,使其更具可读性。

为了方便,只需添加

// MARK: - <#label#>

到您的代码片段。

▽替代方式

这样使用它

private typealias SectionName = ViewController
private extension SectionName  {
    // Your methods
}

这不仅可以添加标记(就像pragma mark一样),还可以很好地隔离代码。

Add a to-do item: Insert a comment with the prefix TODO:. For example: // TODO: [your to-do item]. Add a bug fix reminder: Insert a comment with the prefix FIXME:. For example: // FIXME: [your bug fix reminder]. Add a heading: Insert a comment with the prefix MARK:. For example: // MARK: [your section heading]. Add a separator line: To add a separator above an annotation, add a hyphen (-) before the comment portion of the annotation. For example: // MARK: - [your content]. To add a separator below an annotation, add a hyphen (-) after the comment portion of the annotation. For example: // MARK: [your content] -.