[关闭]
@fiy-fish 2017-08-17T22:04:07.000000Z 字数 5280 阅读 1486

Swift 文档(注释)

iOS



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

简单的注释方法:

  1. /**
  2. Lorem ipsum dolor sit amet.
  3. @param bar Consectetur adipisicing elit.
  4. @return Sed do eiusmod tempor.
  5. */
  6. func foo(bar: String) -> AnyObject { ... }

效果图

注释效果图
完整一点的注释方法:

  1. /**
  2. Lorem ipsum dolor sit amet.
  3. - parameter bar: Consectetur adipisicing elit.
  4. - returns: Sed do eiusmod tempor.
  5. */
  6. func foo(bar: String) -> AnyObject { ... }

注释效果图


### 基础标志

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

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

> 支持基本的 `MarkDown` 语法
  1. /**
  2. # Lists
  3. You can apply *italic*, **bold**, or `code` inline styles.
  4. ## Unordered Lists
  5. - Lists are great,
  6. - but perhaps don't nest
  7. - Sub-list formatting
  8. - isn't the best.
  9. ## Ordered Lists
  10. 1. Ordered lists, too
  11. 2. for things that are sorted;
  12. 3. Arabic numerals
  13. 4. are the only kind supported.
  14. */

参数和返回值

- 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))
    }
```

文件描述

  1. /**
  2. The area of the `Shape` instance.
  3. Computation depends on the shape of the instance.
  4. For a triangle, `area` will be equivalent to:
  5. let height = triangle.calculateHeight()
  6. let area = triangle.base * height / 2
  7. */
  8. var area: CGFloat?

swift 稳当主食

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

  1. /**
  2. The perimeter of the `Shape` instance.
  3. Computation depends on the shape of the instance, and is
  4. equivalent to:
  5. ```
  6. // Circles:
  7. let perimeter = circle.radius * 2 * CGFloat(M_PI)
  8. // Other shapes:
  9. let perimeter = shape.sides.map { $0.length }
  10. .reduce(0, combine: +)
  11. ```
  12. */
  13. var perimeter: CGFloat { get }

swift zhu


完整的例子

  1. import Foundation
  2. /// 🚲 A two-wheeled, human-powered mode of transportation.
  3. class Bicycle {
  4. /**
  5. Frame and construction style.
  6. - Road: For streets or trails.
  7. - Touring: For long journeys.
  8. - Cruiser: For casual trips around town.
  9. - Hybrid: For general-purpose transportation.
  10. */
  11. enum Style {
  12. case Road, Touring, Cruiser, Hybrid
  13. }
  14. /**
  15. Mechanism for converting pedal power into motion.
  16. - Fixed: A single, fixed gear.
  17. - Freewheel: A variable-speed, disengageable gear.
  18. */
  19. enum Gearing {
  20. case Fixed
  21. case Freewheel(speeds: Int)
  22. }
  23. /**
  24. Hardware used for steering.
  25. - Riser: A casual handlebar.
  26. - Café: An upright handlebar.
  27. - Drop: A classic handlebar.
  28. - Bullhorn: A powerful handlebar.
  29. */
  30. enum Handlebar {
  31. case Riser, Café, Drop, Bullhorn
  32. }
  33. /// The style of the bicycle.
  34. let style: Style
  35. /// The gearing of the bicycle.
  36. let gearing: Gearing
  37. /// The handlebar of the bicycle.
  38. let handlebar: Handlebar
  39. /// The size of the frame, in centimeters.
  40. let frameSize: Int
  41. /// The number of trips travelled by the bicycle.
  42. private(set) var numberOfTrips: Int
  43. /// The total distance travelled by the bicycle, in meters.
  44. private(set) var distanceTravelled: Double
  45. /**
  46. Initializes a new bicycle with the provided parts and specifications.
  47. - Parameters:
  48. - style: The style of the bicycle
  49. - gearing: The gearing of the bicycle
  50. - handlebar: The handlebar of the bicycle
  51. - frameSize: The frame size of the bicycle, in centimeters
  52. - Returns: A beautiful, brand-new bicycle, custom built
  53. just for you.
  54. */
  55. init(style: Style, gearing: Gearing, handlebar: Handlebar, frameSize centimeters: Int) {
  56. self.style = style
  57. self.gearing = gearing
  58. self.handlebar = handlebar
  59. self.frameSize = centimeters
  60. self.numberOfTrips = 0
  61. self.distanceTravelled = 0
  62. }
  63. /**
  64. Take a bike out for a spin.
  65. - Parameter meters: The distance to travel in meters.
  66. */
  67. func travel(distance meters: Double) {
  68. if meters > 0 {
  69. distanceTravelled += meters
  70. ++numberOfTrips
  71. }
  72. }
  73. }

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

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


MARK / TODO / FIXME

下面的字符 会显示在 代码导航栏中
- // MARK: (As with #pragma, marks followed by a single dash (-) will be preceded with a horizontal divider)
- // TODO:
- // FIXME:

如图, 就是下面代码的导航栏
![SWIFT文档][7]
  1. // MARK: CustomStringConvertible
  2. extension Bicycle: CustomStringConvertible {
  3. public var description: String {
  4. var descriptors: [String] = []
  5. switch self.style {
  6. case .Road:
  7. descriptors.append("A road bike for streets or trails")
  8. case .Touring:
  9. descriptors.append("A touring bike for long journeys")
  10. case .Cruiser:
  11. descriptors.append("A cruiser bike for casual trips around town")
  12. case .Hybrid:
  13. descriptors.append("A hybrid bike for general-purpose transportation")
  14. }
  15. switch self.gearing {
  16. case .Fixed:
  17. descriptors.append("with a single, fixed gear")
  18. case .Freewheel(let n):
  19. descriptors.append("with a \(n)-speed freewheel gear")
  20. }
  21. switch self.handlebar {
  22. case .Riser:
  23. descriptors.append("and casual, riser handlebars")
  24. case .Café:
  25. descriptors.append("and upright, café handlebars")
  26. case .Drop:
  27. descriptors.append("and classic, drop handlebars")
  28. case .Bullhorn:
  29. descriptors.append("and powerful bullhorn handlebars")
  30. }
  31. descriptors.append("on a \(frameSize)\" frame")
  32. // FIXME: Use a distance formatter
  33. descriptors.append("with a total of \(distanceTravelled) meters traveled over \(numberOfTrips) trips.")
  34. // TODO: Allow bikes to be named?
  35. return descriptors.joinWithSeparator(", ")
  36. }
  37. }

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

  1. let bike = Bicycle(style: .Road, gearing: .Freewheel(speeds: 8), handlebar: .Drop, frameSize: 53)
  2. bike.travel(distance: 1_500) // Trip around the town
  3. bike.travel(distance: 200) // Trip to the store
  4. print(bike)
  5. // "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."
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注