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


当前回答

对于那些对使用扩展和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
    }

}

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

其他回答

我认为Extensions是一个更好的方式而不是#pragma mark。

使用扩展前的代码:

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
    ...

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        ...
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        ...
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        ...
    }
}

使用扩展后的代码:

class ViewController: UIViewController {
    ...
}

extension ViewController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        ...
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        ...
    }
}

extension ViewController: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
       ...
    }
}

试试这个:

// MARK: Reload TableView

func reloadTableView(){

    tableView.reload()
}

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

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

在Objective-C中使用Pragma标记- [SOME TEXT HERE]将几个函数通过行分隔分组在一起。

在Swift中,您可以使用MARK, TODO或FIXME来实现这一点

i. MARK: //MARK: viewDidLoad

这将创建一条水平线,函数分组在viewDidLoad下(如截图1所示)

ii. 待办事项: //待办事项: - viewDidLoad

这将把函数分组在TODO: - viewDidLoad类别下(如截图2所示)

iii. FIXME : //FIXME - viewDidLoad

这将把函数分组在FIXME下:- viewDidLoad类别(如截图3所示)

查看apple文档了解详细信息。

有三个选项可以在Swift中添加#pragma_mark:

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

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

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

注意:用于添加分隔符