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


当前回答

试试这个:

// MARK: Reload TableView

func reloadTableView(){

    tableView.reload()
}

其他回答

Use

// MARK: SectionName

or

// MARK: - SectionName

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

为了方便,只需添加

// MARK: - <#label#>

到您的代码片段。

▽替代方式

这样使用它

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

这不仅可以添加标记(就像pragma 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)

Pragma标记是一种提高代码可读性的方法。pragma注释会像Xcode跳跃栏上的标签一样出现。

//MARK:  <Your comment goes here>

示例:在代码中,

//MARK: Properties

// MARK: View Life cycle

//MARK: Helper methods

这是它在Xcode跳转栏中的显示方式。

对于那些对使用扩展和pragma标记感兴趣的人(如第一条评论所述),下面是如何从Swift工程师实现它:

import UIKit

class SwiftTableViewController: UITableViewController {

    init(coder aDecoder: NSCoder!) {
        super.init(coder: aDecoder)

    }

    override func viewDidLoad() {
        super.viewDidLoad()

    }
}

extension SwiftTableViewController {
    override func numberOfSectionsInTableView(tableView: UITableView?) -> Int {
        return 1
    }

    override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int {
        return 5
    }

    override func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell? {
        let cell = tableView?.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as UITableViewCell;

        cell.textLabel.text = "Hello World"

        return cell
    }

}

这也不一定是最佳实践,但如果您愿意,可以这样做。

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

#warning("Some string to display")

and

#error("Some error to display")

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