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


当前回答

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更语义的级别上。

在Xcode 11中,他们添加了小地图,可以激活编辑器->小地图。

小地图将显示每个标记文本在代码中快速定位。 每个标记都写为// mark: Variables

我认为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) {
       ...
    }
}

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

Use

// MARK: SectionName

or

// MARK: - SectionName

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

为了方便,只需添加

// MARK: - <#label#>

到您的代码片段。

▽替代方式

这样使用它

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

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