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


当前回答

你可能也会对Swift 4.2 / XCode 10编译器指令感兴趣

#warning("Some string to display")

and

#error("Some error to display")

当你真的不想错过什么东西时,它可能会很有用。

其他回答

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)

//MARK:在Xcode 6.3.2中似乎不工作。然而,这是我所做的让它工作:

1)代码:

import Cocoa

class MainWindowController: NSWindowController {

    //MARK: - My cool methods

    func fly() {
    }

    func turnInvisible() {

    }
}

2)在跳转栏中添加//MARK:注释时没有任何变化。然而,如果我点击跳转栏中最右边的名字,在我的例子中,它说的是MainWindowController(带有一个领先的C图标),然后一个弹出窗口将显示显示//MARK:注释的效果,即一个标题说“my cool methods”:

3)我还注意到,如果我点击我的代码中的一个方法,那么这个方法就会变成跳转栏中最右边的条目。为了让MainWindowController(带有一个C图标)成为跳转栏中最右边的条目,我必须单击方法上面的空白。

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] -.

你可以使用// MARK:


也有讨论认为,自由使用类扩展可能是一种更好的实践。由于扩展可以实现协议,例如,你可以把你所有的表视图委托方法放在一个扩展中,并将你的代码分组在一个比#pragma mark更语义的级别上。

试试这个:

// MARK: Reload TableView

func reloadTableView(){

    tableView.reload()
}