Swift編碼規範之註釋規範:文件註釋、文檔註釋、代碼註釋、使用地標註釋

前面說到Swift註釋的語法有兩種:單行註釋(//)和多行註釋(/*...*/)。這裏來介紹一下他們的使用規範。

一、文件註釋就在每個文件開頭添加註釋,文件註釋一般包括以下信息:版權信息、文件名、所在模塊、做者信息、歷史版本信息、文件內容和做用等。
下面看一個文件註釋的示例:
/*
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
*/
這個註釋只是提供了版權信息、文件內容和歷史版本信息等,文件註釋要根據本身實際狀況包括內容。

二、文檔註釋
文檔註釋就是這種註釋內容可以生成API幫助文檔。文檔註釋主要對類型、屬性、方法或函數等功能。
文檔註釋是稍微將單行註釋(//)和多行註釋(/*...*/)作一點「手腳」後,就成爲了文檔註釋,單行文檔註釋(///)和多行文檔註釋(/**...*/)。
下面代碼示例:
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文件

三、代碼註釋
程序代碼中處理文檔註釋還須要在一些關鍵的地方添加代碼註釋,文檔註釋通常是給一些看不到源代碼的人看的幫助文檔,而代碼註釋是給閱讀源代碼人蔘考的。代碼註釋通常是採用單行註釋(//)和多行註釋(/*...*/)。
有的時候也會在代碼的尾端進行註釋,這要求註釋內容極短,應該在有足夠的空白來分開代碼和註釋。尾端註釋示例代碼以下:
init(timeout: NSTimeInterval) {
     self.timeout = timeout //初始化
}

四、使用地標註釋
隨着編碼過程深刻,工程代碼量會增長,任何在這大量的代碼中能快速找到須要方法或者是剛纔修改過代碼呢?
在Swift代碼中使用地標註釋,而後就可使用Xcode工具在代碼中快速查找了。地標註釋有三個:
 MARK,用於方法或函數的註釋。
 TODO,表示這裏代碼有沒有完成,還要處理。
 FIXME,表示這裏修改了代碼。
這些註釋會出如今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 協議方法 //使用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 協議方法 //使用MARK註釋
    func tableView(tableView: UITableView,
                                        didSelectRowAtIndexPath indexPath: NSIndexPath) {
        ...
    }
}
上述代碼中使用三種地標註釋,在使用時候後面要跟有一個冒號(:)。
註釋以後若是使用呢?打開Xcode的 Jump Bar,以下圖,這些地標註釋會在下拉列表中粗體顯示,點擊列表項就會跳轉到註釋行。
相關文章
相關標籤/搜索