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


当前回答

Use

// MARK: SectionName

or

// MARK: - SectionName

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

为了方便,只需添加

// MARK: - <#label#>

到您的代码片段。

▽替代方式

这样使用它

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

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

其他回答

对于那些对使用扩展和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中添加#pragma_mark:

1) // MARK: -你的文字在这里-

2) // TODO: -你的文本在这里-

3) // FIXME: -你的文本在这里-

注意:用于添加分隔符

今天早上在WWDC上,苹果工程师在Swift实验室确认,目前没有任何#pragma或类似的东西,他们认为这是一个bug,很快就会出现,所以我猜是beta 2,我希望。

不管怎样,它在路上了。


Xcode现在支持//MARK:, //TODO:和//FIXME标记来注释你的代码和 在跳转栏中列出它们

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

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

试试这个:

// MARK: Reload TableView

func reloadTableView(){

    tableView.reload()
}