在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: Reload TableView
func reloadTableView(){
tableView.reload()
}
苹果在最新版本的“构建可可应用程序”中表示,
Swift编译器不包括预处理器。相反,它需要 编译时属性、构建配置和 语言特性来完成相同的功能。对于这个 原因是,在Swift中不导入预处理器指令。
#字符似乎仍然是你处理各种构建配置和类似事情的方式,但看起来他们试图减少你对大多数预处理的需求,并将你转发到其他语言特性。也许这是为了帮助Playgrounds和REPL的操作尽可能接近完全编译的代码。
在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文档了解详细信息。
//MARK:在Xcode 6.3.2中似乎不工作。然而,这是我所做的让它工作:
1)代码:
import Cocoa
class MainWindowController: NSWindowController {
//MARK: - My cool methods
func fly() {
}
func turnInvisible() {
}
}
2)在跳转栏中添加//MARK:注释时没有任何变化。然而,如果我点击跳转栏中最右边的名字,在我的例子中,它说的是MainWindowController(带有一个领先的C图标),然后一个弹出窗口将显示显示//MARK:注释的效果,即一个标题说“my cool methods”:
3)我还注意到,如果我点击我的代码中的一个方法,那么这个方法就会变成跳转栏中最右边的条目。为了让MainWindowController(带有一个C图标)成为跳转栏中最右边的条目,我必须单击方法上面的空白。
对于那些对使用扩展和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
}
}
这也不一定是最佳实践,但如果您愿意,可以这样做。