在Objective C中,我可以使用#pragma mark来标记符号导航器中的代码片段。由于这是一个C预处理器命令,所以在Swift中不可用。在Swift中有替代品吗,或者我必须使用丑陋的评论吗?
当前回答
我认为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) {
...
}
}
其他回答
有三个选项可以在Swift中添加#pragma_mark:
1) // MARK: -你的文字在这里-
2) // TODO: -你的文本在这里-
3) // FIXME: -你的文本在这里-
注意:用于添加分隔符
Xcode 8现在像下面这样处理它,在方法下拉菜单中显示如下:
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)
在Objective-C代码中,Xcode检测像// MARK: - foo这样的注释,它比#pragma更可移植。但这些似乎也没有被采纳(目前?)
编辑:在Xcode 6 beta 4中修复。
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] -.