在Objective C中,我可以使用#pragma mark来标记符号导航器中的代码片段。由于这是一个C预处理器命令,所以在Swift中不可用。在Swift中有替代品吗,或者我必须使用丑陋的评论吗?
当前回答
你可以使用// MARK:
也有讨论认为,自由使用类扩展可能是一种更好的实践。由于扩展可以实现协议,例如,你可以把你所有的表视图委托方法放在一个扩展中,并将你的代码分组在一个比#pragma mark更语义的级别上。
其他回答
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
}
}
这也不一定是最佳实践,但如果您愿意,可以这样做。
在Objective-C代码中,Xcode检测像// MARK: - foo这样的注释,它比#pragma更可移植。但这些似乎也没有被采纳(目前?)
编辑:在Xcode 6 beta 4中修复。
专业程序员必须使用这个标签来获得好的代码。 这对团队合作也有好处。
// MARK: example Web Service start here
// TODO: example 1
// FIXME: Please change BASE url before live
像这样的方法很容易找到
苹果在最新版本的“构建可可应用程序”中表示,
Swift编译器不包括预处理器。相反,它需要 编译时属性、构建配置和 语言特性来完成相同的功能。对于这个 原因是,在Swift中不导入预处理器指令。
#字符似乎仍然是你处理各种构建配置和类似事情的方式,但看起来他们试图减少你对大多数预处理的需求,并将你转发到其他语言特性。也许这是为了帮助Playgrounds和REPL的操作尽可能接近完全编译的代码。