Swift 文档(注释) 示范

标签(空格分隔): iOS


  • 翻译自Swift Documentation

好的文档注释, 简洁如一的代码风格更能体现一个开发者的价值, 这里主要介绍 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

你可能感兴趣的:(Swift 文档(注释) 示范)