一般我们写程序时,都会为代码加上一些注释,一个是为了给别人看,另一个原因就是如果项目越写越大时,可能就忘了之前写的函数或类是什么作用了,所以养成边写代码编写注释甚至是实现功能前就加上注释的习惯是很重要的。
那么,在Swift里是怎么为代码加注释,加了注释又会有什么效果呢。 大部分语言的单行注释是两个/
,多行注释是/
加*
号。Swift当然也支持这种注释。
// 单行注释
/*
多行注释
*/
但是在Swift里,除了上面的两种注释外,还支持使用Markdown编写注释,但是如果要让Markdown编写的注释可以在XCode的Quick Help里可以展示,则单行注释需要使用三个/
,多行注释开头需要使用/**
,结尾*/
。否则,注释里写的Markdown是不会被识别出来的,在Quick Help里也无法查看,
/// 单行注释,支持*Markdown*
/**
多行注释
*/
单词分隔符
在注释中还定义了一些特殊的文字分隔符作为注释的标记,比如下图中可以给方法备注上作者。需要注意的是,-
前后需要空格, 另外Author:
中的Author单词对大小写无严格规定,但是一般按照大驼峰命名规则写。也就是单词首字母大写。
支持的单词分隔符有:(要获取最新的可以看苹果官方文档):
Attention
Author
Authors
Bug
Complexity
Copyright
Date
Experiment
Important
Invariant
Note
Parameter
Parameters
Postcondition
Precondition
Remark
Returns
Requires
SeeAlso
Since
Throws
ToDo
Version
Warning
用法(-
也可用+
或*
代替)
/**
- Attention: description
- Author: author name
- Authors: author name
- Bug: this is a bug, fix it.
*/
/**
Play a song.
- parameter song: The song you want play.
*/
func play(song songName: String) {
}
/**
Send a message to someone.
- parameter message: message want send.
- parameter user: send message to user.
*/
func send(msg message: String, to user: String) {
}
由多个参数时除了分行写parameter外,还有下面这种写法:
/**
Send a message to someone.
- parameters:
- message: message want send.
- user: send message to user.
*/
func send(msg message: String, to user: String) {
}
需要注意的是,parameters 下面写的参数需要往里缩进一格(加一个tab或者两个空格都可以)
/**
- parameters:
- min: min number
- max: max number
- returns:
number between min and max
*/
func returnsExample(min: Int, max: Int) -> Int{
// TODO: - finish it
return 0
}
注释中加入无序列表
/**
An example of using a *bulleted list*
* item 1
* item 2
* item 2.1
* item 3
*/
func bulletedListExample() {
}
有序列表
/**
An example of using a *numbered list*
1. Fruit
1. Apple
2. Banana
2. Vegetable
1. Cabbage
*/
func numberedListExample() {
}
在注释中加上示例代码
方式1: 将示例代码缩进
/**
An example of using a *code block*
A loop to print each character on a seperate line
for s in str.characters {
print(s)
}
*/
func codeBlockExample(_ str: String) {
for s in str.characters {
print(s)
}
}
方式二:
给注释中的文字加粗或重点标注
/**
Markup uses simple character-based delimiters to mark formatted text in *playgrounds* and in *Quick Help* for Swift symbols.
Some of the delimiters are used for both rendered `playground` documentation and in `Quick Help`. Other delimiters are used with _either playgrounds or with Quick Help_. The documentation for each delimiter **includes** information __on where it can be used__.
*/
func importantCharacters(){
}
注释中插入链接
/**
An example of using the seealso field
- Note:
[SeeAlso](https://developer.apple.com/library/content/documentation/Xcode/Reference/xcode_markup_formatting_ref/Links.html)
*/
func linksExample() {
}
总结
注释算是项目中非常重要的内容,这里总结的只是我觉得在XCode中写代码会比较常用的注释,其实官网还有一些强大的注释是给Playground用的,这里就不总结了,自己去看吧。在这次总结里面我从苹果的文档中尝试失败的有两个,一个是SeeAlso,另一个是在注释里插入网络图片,大家可以尝试一下,欢迎留言指正。另外,可以使用快捷键cmd+opt+/
直接在方法或属性上插入注释,如果快捷键没用,可能是被当前其他应用给占据了,可以把快捷键在XCode中修改为其他自己熟悉的快捷键。