代碼大家都會寫,但是把注釋寫好卻是一個技識訓,
下面這段話,很好的說明了寫好注釋的感覺:
注釋代碼很像清潔你的廁所——你不想干,但如果你做了,這絕對會給你和你的客人帶來更愉悅的體驗,—— Ryan Campbell
Objective-C的代碼注釋
很久很久以前,在Xcode還可以安裝插件的時代,iOSer都通過VVDocument來撰寫代碼注釋的,
代碼注釋的風格一般都是這樣的,代碼出自SDWebImageManager.h
/**
* Controls which image should be downloaded when the image is not found in the cache.
*
* @param imageManager The current `SDWebImageManager`
* @param imageURL The url of the image to be downloaded
*
* @return Return NO to prevent the downloading of the image on cache misses. If not implemented, YES is implied.
*/
- (BOOL)imageManager:(nonnull SDWebImageManager *)imageManager shouldDownloadImageForURL:(nonnull NSURL *)imageURL;
/**
* Controls the complicated logic to mark as failed URLs when download error occur.
* If the delegate implement this method, we will not use the built-in way to mark URL as failed based on error code;
@param imageManager The current `SDWebImageManager`
@param imageURL The url of the image
@param error The download error for the url
@return Whether to block this url or not. Return YES to mark this URL as failed.
*/
* (BOOL)imageManager:(nonnull SDWebImageManager *)imageManager shouldBlockFailedURL:(nonnull NSURL *)imageURL withError:(nonnull NSError *)error;
- OC的注釋是通過/** */這樣的形式進行撰寫的,
分隔符使用的是這種風格:
#pragma mark - 這個是一個分割符

- 需要注意的是這個-非常的重要,通過這個-,在查看代碼的時候,可以生成分隔線,讓代碼結構看的更為清晰,
Swift的代碼注釋
隨著Swift語言發布,在Swift中撰寫注釋的風格就所有不同了:
extension NSObject {
/// 物件獲取類的字串名稱
public var className: String {
return runtimeType.className
}
/// 類獲取類的字串名稱
public static var className: String {
return String(describing: self)
}
/// NSObject物件獲取型別
public var runtimeType: NSObject.Type {
return type(of: self)
}
/// 這是一個例子函式
/// - Parameter arg:
/// - Parameter argument: 傳入Int型別的引數
/// - Returns: 回傳Int型別的引數
public func afunction(argument: Int) -> Int {
return argument
}
}
- Swift的注釋是通過/// 這樣的形式進行撰寫的,
分隔符使用的是這種風格:
//MARK: - 系結

- Swift中的//MARK:這個-也是起到生成分隔線的作用,
Objective-C和Swift的注釋風格現在已經統一
如果你現在通過**alt+cmd+/**在OC和Swift中撰寫注釋的時候,就會發現現在的注釋都變成了Swift的這個中風格了:
/// 主要產品
/// - Parameter data: 出入字典 key: companyProducts
/// - Returns: CompanyCellModelable
func setProductModel(_ data: CompanyModel.CompanyProducts?) -> CompanyCellModelable? {
- 我個人建議是:以前代碼注釋就讓它去吧,現在就都是用這個統一風格,
快速修改注釋
一個函式寫好了,注釋也寫好,但是有的時候計劃沒有變化快,函式添加了新的引數,這個注釋難道要手動添加?
別急,其實Xcode也為我們提供了快捷方式,我們繼續看例子,這個函式我在之前的基礎上添加了一個num引數,但是注釋還是之前的樣子:

cmd+滑鼠左鍵點擊,我們可以看到左側出現了一個選單,點擊Add Documentation

我們需要添加的引數它就來了,這樣就可以直接添加注釋了,

大家有興趣可以把選單的選項都點擊試試,也許有意外的驚喜,比如Convert Function to Async,await/async,
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/332124.html
標籤:其他
