@fiy-fish
2017-08-17T22:04:07.000000Z
字数 5280
阅读 1486
iOS
好的文档注释, 简洁如一的代码风格更能体现一个开发者的价值, 这里主要介绍 swfit 中的文档注释
简单的注释方法:
/**
Lorem ipsum dolor sit amet.
@param bar Consectetur adipisicing elit.
@return Sed do eiusmod tempor.
*/
func foo(bar: String) -> AnyObject { ... }
效果图
完整一点的注释方法:
/**
Lorem ipsum dolor sit amet.
- parameter bar: Consectetur adipisicing elit.
- returns: Sed do eiusmod tempor.
*/
func foo(bar: String) -> AnyObject { ... }
### 基础标志
多行注释: /** ... */
单行注释: ///
支持下面的效果:
- 空行分段
- 无序列表, 可以在前面加上-, +, *, •
中的一个
- 有序列表, 使用 (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?
也可以在代码前后加上 符号` 或者 ~ 来实现同样的 代码块效果
/**
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 }
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 + 单击 枚举类型, 会弹出类型说明如图
使用上面的操作 弹出方法注释
下面的字符 会显示在 代码导航栏中
- // 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."