在Objective C中,我可以使用#pragma mark来标记符号导航器中的代码片段。由于这是一个C预处理器命令,所以在Swift中不可用。在Swift中有替代品吗,或者我必须使用丑陋的评论吗?
当前回答
//# MARK: - Spinner Class Methods
在冒号和描述之间添加一行,以插入分隔线。这有助于更好地组织代码。上面的代码和截图使用了包含一行的MARK注释。
//#标记:-文本方法(LINE) //#标记:文本方法(NO LINE)
这只适用于MARK注释。
其他回答
你可以使用// MARK:
也有讨论认为,自由使用类扩展可能是一种更好的实践。由于扩展可以实现协议,例如,你可以把你所有的表视图委托方法放在一个扩展中,并将你的代码分组在一个比#pragma mark更语义的级别上。
//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图标)成为跳转栏中最右边的条目,我必须单击方法上面的空白。
有三个选项可以在Swift中添加#pragma_mark:
1) // MARK: -你的文字在这里-
2) // TODO: -你的文本在这里-
3) // FIXME: -你的文本在这里-
注意:用于添加分隔符
我认为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) {
...
}
}
对于那些对使用扩展和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
}
}
这也不一定是最佳实践,但如果您愿意,可以这样做。