Swift 文档(注释) 示范

标签(空格分隔): iOS



好的文档注释, 简洁如一的代码风格更能体现一个开发者的价值, 这里主要介绍 swfit 中的文档注释

简单的注释方法:

/**
    Lorem ipsum dolor sit amet.

    @param bar Consectetur adipisicing elit.

    @return Sed do eiusmod tempor.
*/
func foo(bar: String) -> AnyObject { ... }

效果图

![注释效果图][1]
完整一点的注释方法:

/**
    Lorem ipsum dolor sit amet.

    - parameter bar: Consectetur adipisicing elit.

    - returns: Sed do eiusmod tempor.
*/
func foo(bar: String) -> AnyObject { ... }

![注释效果图][2]


注释的基础知识

多行注释: /** ... */
单行注释: ///

  • 支持下面的效果:

    • 空行分段
    • 无序列表, 可以在前面加上-, +, *, • 中的一个
    • 有序列表, 使用 (1, 2, 3, …) 或者 1):
    • 标题: # 下划线:=或者-
    • 甚至 图片 image 和 链接 links , Xcode 也支持

    支持基本的 MarkDown 语法

/**
    # Lists

    You can apply *italic*, **bold**, or `code` inline styles.

    ## Unordered Lists

    - Lists are great,
    - but perhaps don't nest
    - Sub-list formatting

      - isn't the best.

    ## Ordered Lists

    1. Ordered lists, too
    2. for things that are sorted;
    3. Arabic numerals
    4. are the only kind supported.
*/

参数和返回值

- Parameters: 参数部分以`parameter 参数名`开头, 后面接参数的描述

- Return values: 以`Return 返回值` 开头, 后面接参数说明

- Throws errors : 以`Throws `开头, 描述错误信息

```
/**
Repeats a string `times` times.

- Parameter str:   The string to repeat.
- Parameter times: The number of times to repeat `str`.

- Throws: `MyError.InvalidTimes` if the `times` parameter 
    is less than zero.

- Returns: A new string with `str` repeated `times` times.
*/
func repeatString(str: String, times: Int) throws -> String {
guard times >= 0 else { throw MyError.InvalidTimes }
return Repeat(count: 5, repeatedValue: "Hello").joinWithSeparator("")
}
```

当参数很多时, 我们也可以只写一个 `Parameters:` 如下面的写法

 ```
    /// Returns the magnitude of a vector in three dimensions
    /// from the given components.
    ///
    /// - Parameters:
    ///     - x: The *x* component of the vector.
    ///     - y: The *y* component of the vector.
    ///     - z: The *z* component of the vector.
    func magnitude3D(x: Double, y: Double, z: Double) -> Double {
        return sqrt(pow(x, 2) + pow(y, 2) + pow(z, 2))
    }
```

文件描述

  • 注释中有代码块
    /**
    The area of the `Shape` instance.

    Computation depends on the shape of the instance. 
    For a triangle, `area` will be equivalent to:

        let height = triangle.calculateHeight()
        let area = triangle.base * height / 2
*/
var area: CGFloat?

![swift 稳当主食][3]

也可以在代码前后加上 符号` 或者 ~ 来实现同样的 代码块效果

/**
    The perimeter of the `Shape` instance.

    Computation depends on the shape of the instance, and is
    equivalent to: 

    ```
    // Circles:
    let perimeter = circle.radius * 2 * CGFloat(M_PI)

    // Other shapes:
    let perimeter = shape.sides.map { $0.length }
                               .reduce(0, combine: +)
    ```
*/
var perimeter: CGFloat { get }

![swift zhu][4]


完整的例子

import Foundation

/// 🚲 A two-wheeled, human-powered mode of transportation.
class Bicycle {
    /**
        Frame and construction style.

        - Road: For streets or trails.
        - Touring: For long journeys.
        - Cruiser: For casual trips around town.
        - Hybrid: For general-purpose transportation.
    */
    enum Style {
        case Road, Touring, Cruiser, Hybrid
    }

    /**
        Mechanism for converting pedal power into motion.

        - Fixed: A single, fixed gear.
        - Freewheel: A variable-speed, disengageable gear.
    */
    enum Gearing {
        case Fixed
        case Freewheel(speeds: Int)
    }

    /**
        Hardware used for steering.

        - Riser: A casual handlebar.
        - Café: An upright handlebar.
        - Drop: A classic handlebar.
        - Bullhorn: A powerful handlebar.
    */
    enum Handlebar {
        case Riser, Café, Drop, Bullhorn
    }

    /// The style of the bicycle.
    let style: Style

    /// The gearing of the bicycle.
    let gearing: Gearing

    /// The handlebar of the bicycle.
    let handlebar: Handlebar

    /// The size of the frame, in centimeters.
    let frameSize: Int

    /// The number of trips travelled by the bicycle.
    private(set) var numberOfTrips: Int

    /// The total distance travelled by the bicycle, in meters.
    private(set) var distanceTravelled: Double

    /**
        Initializes a new bicycle with the provided parts and specifications.

        - Parameters:
            - style: The style of the bicycle
            - gearing: The gearing of the bicycle
            - handlebar: The handlebar of the bicycle
            - frameSize: The frame size of the bicycle, in centimeters

        - Returns: A beautiful, brand-new bicycle, custom built
          just for you.
    */
    init(style: Style, gearing: Gearing, handlebar: Handlebar, frameSize centimeters: Int) {
        self.style = style
        self.gearing = gearing
        self.handlebar = handlebar
        self.frameSize = centimeters

        self.numberOfTrips = 0
        self.distanceTravelled = 0
    }

    /**
        Take a bike out for a spin.

        - Parameter meters: The distance to travel in meters.
    */
    func travel(distance meters: Double) {
        if meters > 0 {
            distanceTravelled += meters
            ++numberOfTrips
        }
    }
}

当我们 按住 option + 单击 枚举类型, 会弹出类型说明如图
![swift 文档说明][5]

使用上面的操作 弹出方法注释
![swift 文档注释][6]


MARK / TODO / FIXME

  • 下面的字符 会显示在 代码导航栏中

    • // MARK: (As with #pragma, marks followed by a single dash (-) will be preceded with a horizontal divider)
    • // TODO:
    • // FIXME:

    如图, 就是下面代码的导航栏
    ![SWIFT文档][7]

// MARK: CustomStringConvertible

extension Bicycle: CustomStringConvertible {
    public var description: String {
        var descriptors: [String] = []

        switch self.style {
        case .Road:
            descriptors.append("A road bike for streets or trails")
        case .Touring:
            descriptors.append("A touring bike for long journeys")
        case .Cruiser:
            descriptors.append("A cruiser bike for casual trips around town")
        case .Hybrid:
            descriptors.append("A hybrid bike for general-purpose transportation")
        }

        switch self.gearing {
        case .Fixed:
            descriptors.append("with a single, fixed gear")
        case .Freewheel(let n):
            descriptors.append("with a \(n)-speed freewheel gear")
        }

        switch self.handlebar {
        case .Riser:
            descriptors.append("and casual, riser handlebars")
        case .Café:
            descriptors.append("and upright, café handlebars")
        case .Drop:
            descriptors.append("and classic, drop handlebars")
        case .Bullhorn:
            descriptors.append("and powerful bullhorn handlebars")
        }

        descriptors.append("on a \(frameSize)\" frame")

        // FIXME: Use a distance formatter
        descriptors.append("with a total of \(distanceTravelled) meters traveled over \(numberOfTrips) trips.")

        // TODO: Allow bikes to be named?

        return descriptors.joinWithSeparator(", ")
    }
}

最后加上下面的代码, 所有的代码都完成了

let bike = Bicycle(style: .Road, gearing: .Freewheel(speeds: 8), handlebar: .Drop, frameSize: 53)

bike.travel(distance: 1_500) // Trip around the town
bike.travel(distance: 200) // Trip to the store

print(bike)
// "A road bike for streets or trails, with a 8-speed freewheel gear, and classic, drop handlebars, on a 53" frame, with a total of 1700.0 meters traveled over 2 trips."

Xcode 中常用的文档注释 方式都介绍完了, 有了这些注释方法再也不愁自己的代码看不懂了, 希望大家在代码中多写注释, 少坑队友!
[1]: http://nshipster.s3.amazonaws.com/swift-documentation-headerdoc.png
[2]: http://nshipster.s3.amazonaws.com/swift-documentation-new-format.png
[3]: https://hbimg.b0.upaiyun.com/a23aa55c83e11c3e61a57720838ee4218519843b8d3f-E9MgC6_fw658
[4]: https://hbimg.b0.upaiyun.com/91a8e7cc4a230706bd5f6b37c3f51a7cb3c5fe39b229-IvSBCI_fw658
[5]: http://nshipster.s3.amazonaws.com/swift-documentation-enum-declaration.png
[6]: http://nshipster.s3.amazonaws.com/swift-documentation-method-declaration.png
[7]: http://nshipster.s3.amazonaws.com/swift-documentation-xcode-source-navigator.png

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,843评论 6 502
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,538评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,187评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,264评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,289评论 6 390
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,231评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,116评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,945评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,367评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,581评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,754评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,458评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,068评论 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,692评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,842评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,797评论 2 369
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,654评论 2 354

推荐阅读更多精彩内容