原創(chuàng)文章,歡迎轉(zhuǎn)載。轉(zhuǎn)載請注明:關(guān)東升的博客
前面說到Swift注釋的語法有兩種:單行注釋(//)和多行注釋(/.../)。這里來介紹一下他們的使用規(guī)范。
1、文件注釋
文件注釋就在每一個文件開頭添加注釋,文件注釋通常包括如下信息:版權(quán)信息、文件名、所在模塊、作者信息、歷史版本信息、文件內(nèi)容和作用等。
下面看一個文件注釋的示例:
/*
Copyright (C) 2015 Eorient Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Description:
This file contains the foundational subclass of NSOperation.
History:
15/7/22: Created by Tony Guan.
15/8/20: Add socket library
15/8/22: Add math library
*/
這個注釋只是提供了版權(quán)信息、文件內(nèi)容和歷史版本信息等,文件注釋要根據(jù)自己實際情況包括內(nèi)容。
2、文檔注釋
文檔注釋就是這種注釋內(nèi)容能夠生成API幫助文檔。文檔注釋主要對類型、屬性、方法或函數(shù)等功能。
文檔注釋是稍微將單行注釋(//)和多行注釋(/.../)做一點“手腳”后,就成為了文檔注釋,單行文檔注釋(///)和多行文檔注釋(/*.../)。
下面代碼示例:
import Foundation
/**
The protocol that types may implement if they wish to be
notified of significant operation lifecycle events.
*/
protocol OperationObserver {
/// Invoked immediately prior to the `Operation`'s `execute()` method.
func operationDidStart(operation: Operation)
}
代碼中使用了文檔注釋。
可以使用一些工具將這些文檔注釋生成API文件
3、代碼注釋
程序代碼中處理文檔注釋還需要在一些關(guān)鍵的地方添加代碼注釋,文檔注釋一般是給一些看不到源代碼的人看的幫助文檔,而代碼注釋是給閱讀源代碼人參考的。代碼注釋一般是采用單行注釋(//)和多行注釋(/.../)。
有的時候也會在代碼的尾端進(jìn)行注釋,這要求注釋內(nèi)容極短,應(yīng)該在有足夠的空白來分開代碼和注釋。尾端注釋示例代碼如下:
init(timeout: NSTimeInterval) {
self.timeout = timeout //初始化
}
4、使用地標(biāo)注釋
隨著編碼過程深入,工程代碼量會增加,任何在這大量的代碼中能快速找到需要方法或者是剛才修改過代碼呢?
在Swift代碼中使用地標(biāo)注釋,然后就可以使用Xcode工具在代碼中快速查找了。地標(biāo)注釋有三個:
? MARK,用于方法或函數(shù)的注釋。
? TODO,表示這里代碼有沒有完成,還要處理。
? FIXME,表示這里修改了代碼。
這些注釋會出現(xiàn)在Xcode的 Jump Bar中。來看一個示例:
class ViewController: UIViewController,
?UITableViewDataSource, UITableViewDelegate {
var listTeams: [[String:String]]!
override func viewDidLoad() {
super.viewDidLoad()
...
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
//TODO: 釋放資源 //使用TODO注釋
}
// MARK: UITableViewDataSource 協(xié)議方法 //使用MARK注釋
func tableView(tableView: UITableView,
?numberOfRowsInSection section: Int) -> Int {
return self.listTeams.count
}
func tableView(tableView: UITableView,
?cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "CellIdentifier"
let cell: UITableViewCell! = tableView
?.dequeueReusableCellWithIdentifier
cellIdentifier,
?forIndexPath: indexPath) as? UITableViewCell
// FIXME: 修改bug //使用了FIXME注釋
let row = indexPath.row
let rowDict = self.listTeams[row] as [String:String]
...
return cell
}
// MARK: UITableViewDelegate 協(xié)議方法 //使用MARK注釋
func tableView(tableView: UITableView,
?didSelectRowAtIndexPath indexPath: NSIndexPath) {
...
}
}
上述代碼中使用三種地標(biāo)注釋,在使用時候后面要跟有一個冒號(:)。
注釋之后如果使用呢?打開Xcode的 Jump Bar,如下圖,這些地標(biāo)注釋會在下拉列表中粗體顯示,點擊列表項就會跳轉(zhuǎn)到注釋行。
