在Objective C中,我可以使用#pragma mark来标记符号导航器中的代码片段。由于这是一个C预处理器命令,所以在Swift中不可用。在Swift中有替代品吗,或者我必须使用丑陋的评论吗?
当前回答
在Xcode 5之前,预处理器指令#pragma标记存在。
从Xcode 6开始,你必须使用// MARK:
这些预处理器特性允许为源代码编辑器的函数下拉框带来一些结构。
一些例子:
// MARK:
->前面有一个水平分隔符
// MARK: your text goes here
->在下拉列表中将“您的文本放在这里”以粗体显示
// MARK: - your text goes here
->在下拉列表中将“您的文本放在这里”以粗体显示,前面有一个水平分隔符
更新:增加了截图,因为有些人似乎仍然有问题:
其他回答
有三个选项可以在Swift中添加#pragma_mark:
1) // MARK: -你的文字在这里-
2) // TODO: -你的文本在这里-
3) // FIXME: -你的文本在这里-
注意:用于添加分隔符
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] -.
对于那些对使用扩展和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
}
}
这也不一定是最佳实践,但如果您愿意,可以这样做。
在Xcode 11中,他们添加了小地图,可以激活编辑器->小地图。
小地图将显示每个标记文本在代码中快速定位。 每个标记都写为// mark: Variables
Use
// MARK: SectionName
or
// MARK: - SectionName
这将在pragma标记上面加一行,使其更具可读性。
为了方便,只需添加
// MARK: - <#label#>
到您的代码片段。
▽替代方式
这样使用它
private typealias SectionName = ViewController
private extension SectionName {
// Your methods
}
这不仅可以添加标记(就像pragma mark一样),还可以很好地隔离代码。
推荐文章
- 我应该如何从字符串中删除所有的前导空格?- - - - - -斯威夫特
- Swift:理解// MARK
- Swift -转换为绝对值
- Swift编译器错误:“框架模块内的非模块化头”
- 从父iOS访问容器视图控制器
- NSRange从Swift Range?
- 我可以使用范围操作符与if语句在Swift?
- 在Swift中转换字符串为日期
- 点击按钮时如何打开手机设置?
- 在Swift中使用自定义消息抛出错误/异常的最简单方法?
- 编译器错误:带有Objective-C选择器的方法与前面带有相同Objective-C选择器的声明冲突
- 如何在Swift中获得唯一的设备ID ?
- 如何在Swift中获得枚举值的名称?
- 如何调用手势点击在UIView编程在迅速
- 什么是Swift相当于respondsToSelector?