註解 Comments
註解 Comments
對於每一個開發者而言,為程式碼加入註解是一種極好的習慣。雖然它表面上看起來會對開發進度有一定的影響,但這本身亦應當屬於開發過程的一部分。這並不意味著我們要對項目中存在的屬性、函数、類、結構或其它每一樣東西事無巨細地編到文檔中去,這根本是不可能的事情。而是應該「合理」說明解釋,也就是:
- 描述類、方法和屬性的用途,粗略程度要適當。而且最好對調用方法時應當注意的前提條件、事項或限制做重點說明。
- 高亮標出方法的輸入/輸出(參數及返回值)。
- 當你事隔幾個月再次閱讀項目程式碼時,程式碼中每一個方法的用途和每一個屬性的意義你都能輕鬆憶起。
- 當你分享程式碼或庫時,別的開發者能夠很容易就明白這些程式碼要如何使用。
- 若有需要可通過"Jazzy"工具,能生成專業的幫助文件。
// 雙斜線
用來註解方法或區塊說明(MARK) ,注意Xcode會自動忽略不加入文件中
// MARK:- ScrollView Support Method
func scrollforHotCell(_ scrollView: UIScrollView) {
// you code
}
使用 Markdown
/// 三條斜線
文件註解,使用 Xcode預設方法,Editor > Structure > Add Documentation,快速鍵 ⌥⌘/
或是以 /**/ 包覆
/// <#Description#>
///
/// - Parameters:
/// - text: <#text description#>
/// - font: <#font description#>
/// - width: <#width description#>
/// - Returns: <#return value description#>
func heightForView(_ text:String, font:UIFont, width:CGFloat) -> CGFloat{
let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
// label.font = font
label.text = text
label.sizeToFit()
return label.frame.height
}
or
/**
Another complicated function.
- Parameter fullname: The fullname that will be broken into its parts.
- Returns: A *tuple* with the first and last name.
- Remark:
There's a counterpart function that concatenates the first and last name into a full name.
- Precondition: `fullname` should not be nil.
- Requires: Both first and last name should be parts of the full name, separated with a *space character*.
- Todo: Support middle name in the next version.
- Warning: A wonderful **crash** will be the result of a `nil` argument.
- Version: 1.1
- Author: Myself Only
- Note: Too much documentation for such a small function.
*/
func breakFullName(fullname: String) -> (firstname: String, lastname: String) {
let fullnameInPieces = fullname.components(separatedBy: " ")
return (fullnameInPieces[0], fullnameInPieces[1])
}
利用快速幫助Quick Help查看(⌥ + 滑鼠左鍵),效果如下
http://appcoda.com.tw/swift-markdown/
蘋果官方有一個詳盡的文檔列出了全部的關鍵字以及其它內容,請點這裡
用 Jazzy 編譯文件頁面
若專案有需要產出對應的文件時,Jazzy 能夠創建一個能夠單獨瀏覽的網站,并將你在程式碼中書寫的全部文檔都包含到其中
安裝
- 打開終端機
- 輸入: [sudo] gem install jazzy
- 輸入你的密碼
- 等待…
產出文件
- 打開終端機
cd path_to_project_folder
jazzy --min-acl internal
等待…完成
預設輸出的目錄在專案的根目錄下"docs"資料夾內