Original: Documenting Your Swift Code in Xcode Using Markdown
GABRIEL Theodoropoulos
Translator: Kmyhy
Among all the new features of Xcode 7, there is one of the most compelling new features that will allow you to write code files in a better way. Starting with Xcode 7, developers can use powerful Markdown language in their files to do rich text editing, and Markdown uses some special key words to describe different parts of a document, such as parameters, function return values, and so on. To make these structures show different types. One of the great advantages of the new Markdown document is that it allows for a more flexible, thorough and rich customization of text. Of course, if you still want to use the old file style, please refer to the previous tutorial.
For each of the developers, it is a good habit to encode the code. Although it appears to have a certain effect on development, it should also be part of the development process. This does not mean that we are not going to be able to document the nature, function, category, structure, or other things that exist in the project, which is simply impossible. Instead, it should be "reasonable" to file, namely:
- Describe the use of classes, methods, and their nature, roughly to the extent appropriate. It is also best to focus on the prerequisites, items, or limitations that should be noticed when adjusting the method.
- Highlight the input/output of the method (parameters and return values).
- When you read the item code again every few months, you can easily remember the purpose of each method in the code and the meaning of each one.
- When you share a code or library, other developers can easily understand how these codes are used.
- Through some tools (such as Jazzy), we can generate professional help files.
The code files that are encoded in Xcode can be used in three ways to preview:
- Click the option/alt+ mouse key on the name, method name, or category name. You can see a quick overview of the nature, method, or category on the right or bottom of these names.
- Put the mouse in the name, method or name, and you'll open the Quick Help Viewer (Quick help Inspector).
- There are a number of third-party tools that can be used to target documents in the code to help documents, such as Jazzy, which we'll introduce later. Through Jazzy, your files will be translated in Web form, and all of the Web pages are generated into a sub-file under the Item folder, which forms a unique website for you to work with on your site.
The code file should not be an unchanging one, it should be changed as a result of its description of the image (its nature, method, type, structure, and election). There is a law: when new images are added to the code, if you do not add new files immediately, you will never be able to add them. Therefore, we need to nurture and compile the good habits of the files, even if we need to spend some extra time, it is totally worthwhile.
Markdown the basics of the French language base
To use the new file style, you first need to know a bit of marddown language. If you've already learned Markdown language, it's better to skip this part of the content. You can find a lot about Markdown on the web, and if you search for Markdown, you'll get a lot of search results, such as here and here, you might want to browse first.
Although you can find Markdown in any place, I still need to talk about the most basic Markdown language here. The purpose of this article is not to provide a detailed guide to Markdown language, so it is only simple to introduce some of the most basic language methods of Markdown.
You may already know (or know now) that Markdown language is a special character for formatting text, additional resources (links and images), special text blocks (ordered lists, unordered tables, code blocks). These characters are very easy to remember, and at the same time use a web search engine or this list below, and you can emphasize this memory at any time in the brain. If you're familiar with Markdown, you'll find that the languages listed here are very interesting (and easy to remember), and you can compile different formats of documents, such as HTML, PDFs, and so on, with different editors. In HTML, for example, Markdown supports line HTML, meaning that HTML tags can be inserted directly into the text, and these tags are displayed. Of course, using HTML is not the main purpose of Markdown, and our focus is on its own language.
Now, let's make a list of some of the most common language laws in Markdown:
- #text #: Text title, as in HTML. And the last two # means to push it, until. One or more # at the end of text can be omitted.
- **text**: The text of the star will be bold
- *text*: The text of the star will be displayed in italics .
- * Text: Create an unordered list, the item symbol (Note that there is a space behind the star). In addition, you can replace the star with + and ﹣. A maximum of 3 spaces can be used in the back of a star (or two other equal-meaning characters) to indicate the contraction of the list.
- 1. Text: Create an ordered list (number of models).
- [Link text] (http://some-url.com): Transforms the link text into a super link.
- > Text: Creating References.
- Use four (4) spaces or a tab to indicate a code block. As in HTML. tags. Add 4 spaces or a tab character to each level.
- If you do not want to confuse the space and tab characters, you can enclose the code block with a "'" (reverse argument). For example ' Var MyProperty ' will be converted into:var myProperty.
- Another way to represent a code block is to use 4 counter-quotes ("'") and then write the code in the next line.
- A backslash is used for meaning to avoid a character being a part of the Markdown language. For example, the result of the/**this/** is that the text will not be bold and displayed.
The above content is the most important element in the Markdown language. Of course there are other elements in Markdown, and there are many different uses for each of the above elements. You can continue to learn more languages, but the content listed here is enough for the beginner.
If you start to have a little interest in Markdown, you can download a free editor (in the online editor or Mac app) and start practicing. If the editor provides a real-time preview feature, the text will be converted to HTML when you enter it, and you can actually preview the editing text in the same way.
[Ecko_alert color= "Gray"] Editor's language: recommended several Markdown editors: Stackedit (in line editor), Typora,macdown,focused and Ulysses. [/ecko_alert]
Using Markdown
In Swift, there are a few rules that need to be noted when it is time to file a physical image. You can file the content (variables and constants), methods, functions, types, structures, elections, agreements, outreach, and any code structures and physical bodies. The file should be written before the first line of the sound or the beginning of the entity, each line starts with 3 slashes (/ //), or is included in the code block as shown below:
/***/
Two slashes (//) can also produce a note, but they are ignored by Xcode so that they are not displayed as any files. Use a double slash in each code block (for example, in a method), but the first two are used for a complete pair of image annotations.
Let's look at a simple example of Markdown language. Here's a code snippet, and we're doing a file on a piece of paper. After the code fragment, it is a screenshot of the Fast Help (quick assist) that is used in this nature. I recommend that you use Xcode to open a new Playground and try this example.
/// This is an **awesome** documentation line for a really *useful* variable.
var someVar = "This is a variable"
These codes will result in the following:
Note that the word "awesome" is coarse because it is surrounded by two stars, and the word "useful" is italic because it is surrounded by a single star.
Another example, this time, is to file the function in a textual format:
/**
It calculates and returns the outcome of the division of the two parameters.
## Important Notes ##
1. Both parameters are **double** numbers.
2. For a proper result the second parameter *must be other than 0*.
3. If the second parameter is 0 then the function will return nil.
*/
func performDivision(number1: Double, number2: Double) -> Double! {
if number2 != 0 {
return number1 / number2
}
else {
return nil
}
}
If you paste the above code-﹣ into your Playground file and then use the option+ mouse to click the function name, the Quick help will be shown as follows:
It uses two Markdown elements, a text title and an ordered list . At the same time, coarse and italic are used in the sequence table. As you can see, using special characters peculiar to Markdown, we can easily display rich text in documents. The above codes are shown in the Quick Help viewer as follows:
Next, we will use the code block in the function files. Note that, in addition to being used to create code blocks, we will use a counter-reference (') when quoting a function name.
/**
It doubles the value given as a parameter.
### Usage Example: ###
````
let single = 5
let double = doubleValue(single)
print(double)
````
* Use the `doubleValue(_:)` function to get the double value of any number.
* Only ***Int*** properties are allowed.
*/
func doubleValue(value: Int) -> Int {
return value * 2
}
The results are as follows:
Finally, let's compile the file for enum , and then use this in another function. Notice that each case branch in the uses an ISO adds a:
/**
My own alignment options.
````
case Left
case Center
case Right
````
*/
enum AlignmentOptions {
/// It aligns the text on the Left side.
case Left
/// It aligns the text on the Center.
case Center
/// It aligns the text on the Right side.
case Right
}
func doSomething() {
var alignmentOption: AlignmentOptions!
alignmentOption = AlignmentOptions.Left
}
When used in each case, Xcode will show the notes we have written for the case.
Use the keyword
In the Swift code, we don't just have a Markdown tool available. The rich Text format is cool, it makes the document more beautiful, but it's just that. We can also use another tool, called the key word .
Using the key, you can make Xcode self-uses an ISO (which is also valid when using a third-party library to edit the text file) in the default format. The key word can be used to represent different parts of the code structure. For example, there are some key words that are used to highlight the version of the method parameters, the return value, the author of the category, and the function. The number of keys is huge, and not all the keys are so good. Some of these keys are not used much. However, you need to remember the most commonly used keys in your heart, and the rest of the key is followed by random checks.
Then, let's look at some examples of using keywords. The first example is about methods or function parameters:
/**
This is an extremely complicated method that concatenates the first and last name and produces the full name.
- Parameter firstname: The first part of the full name.
- Parameter lastname: The last part of the fullname.
*/
func createFullName(firstname: String, lastname: String) {
let fullname = "\(firstname) \(lastname)"
print(fullname)
}
The final result of the above code is as follows:
Notice that the short horizontal line (-) in front of the key also has a space between the horizontal line and the key. And then it's the name of the argument, and the description or statement of the argument. Note that the number of Parameter keys and the description of the latter must be consistent with the method's actual parameters.
Now, let's make a little change to the above function and return a person's real full name (last name and first name) instead of printing it. We need to add a key to describe the return value of the function:
/**
This is an extremely complicated method that concatenates the first and last name and produces the full name.
- Parameter firstname: The first part of the full name.
- Parameter lastname: The last part of the fullname.
- Returns: The full name as a string value.
*/
func createFullName(firstname: String, lastname: String) -> String {
return "\(firstname) \(lastname)"
}
The final effect is as follows:
It uses two keys (parameter and returns), which are the keys we use the most. But there are some other keys. The following function is the inverse of the above function, breaking a person's full name into first and last names:
/**
Another complicated function.
- Parameter fullname: The fullname that will be broken into its parts.
- Returns: A *tuple* with the first and last name.
- Remark:
There‘s a counterpart function that concatenates the first and last name into a full name.
- SeeAlso: `createFullName(_:lastname:)`
*/
func breakFullName(fullname: String) -> (firstname: String, lastname: String) {
let fullnameInPieces = fullname.componentsSeparatedByString(" ")
return (fullnameInPieces[0], fullnameInPieces[1])
}
Here are the new keys:Remark and seealso. The former is used to highlight certain important or special contents, so that the reader can notice this place at a glance (or you should be able to cause a re-view of this place). The seealso keyword is used in another place where the code is quoted (for example, in this case, we refer to the previous function) or provide a real URL here. The quick help for Xcode is shown as:
Suppose you put the above-mentioned function in a library and divide it into other developers. To make your job more perfect, you might want to let the user of the function know two things (or use a pre-condition): Thefullnameparameters cannot be empty, and the FullName string should contain a space so that it is divided into two parts, otherwise the function does not work correctly. This requires the use of two other keys, precondition and Requires. We need to modify the text of the above function to:
/**
Another complicated function.
- Parameter fullname: The fullname that will be broken into its parts.
- Returns: A *tuple* with the first and last name.
- Remark:
There‘s a counterpart function that concatenates the first and last name into a full name.
- SeeAlso: `createFullName(_:lastname:)`
- Precondition: `fullname` should not be nil.
- Requires: Both first and last name should be parts of the full name, separated with a *space character*.
*/
func breakFullName(fullname: String) -> (firstname: String, lastname: String) {
let fullnameInPieces = fullname.componentsSeparatedByString(" ")
return (fullnameInPieces[0], fullnameInPieces[1])
}
Next, you might want to make some changes to the function at some point in the future and record this plan in case you forget it:
-Todo:support middle name in the next version.
You can also use the warnings, version, author , and notes keys:
/**
Another complicated function.
- Parameter fullname: The fullname that will be broken into its parts.
- Returns: A *tuple* with the first and last name.
- Remark:
There‘s a counterpart function that concatenates the first and last name into a full name.
- SeeAlso: `createFullName(_:lastname:)`
- Precondition: `fullname` should not be nil.
- Requires: Both first and last name should be parts of the full name, separated with a *space character*.
- Todo: Support middle name in the next version.
- Warning: A wonderful **crash** will be the result of a `nil` argument.
- Version: 1.1
- Author: Myself Only
- Note: Too much documentation for such a small function.
*/
func breakFullName(fullname: String) -> (firstname: String, lastname: String) {
let fullnameInPieces = fullname.componentsSeparatedByString(" ")
return (fullnameInPieces[0], fullnameInPieces[1])
}
This is shown in Quick help:
The details of the files depend on you. For the core and important codes, there is no doubt that you need to do a detailed text file as in the previous example, but for the minor code, you just need to compile some basic documents.
Apple official has a detailed file listing all the key words and other content, you can visit the links below and you'll see the details of the Markdown language method. This document is definitely worth a look, please click here.
Editing a text file with Jazzy
Jazzy is a powerful tool for translating the notes from the Objective-c or Swift code into an Apple-style help file. In fact, Jazzy is able to create a Web site that is individually available and contains all the documents you have written in the code. It's a command-line tool, but it's really simple to use.
I'm not going to talk about Jazzy's work machine, you can find everything you want to know on its GitHub page. It is also possible to see the conditions required to use it and how it is installed. The whole Cheng is very simple, and all you need to do is simply:
- Open Terminal Program
- Input:[sudo] gem install jazzy
- Enter your password.
- Wait...
For the use of your test Jazzy, I wrote a small app that you can download from here. The app is actually very simple (and doesn't have much actual functionality at the same time), but it's based on the basics of the previous example. It can synthesize the full name of a person's surname and name, and break the full name into first and last names.
In this app, I've written some files, just like we discussed earlier. Although the app is intended only for demonstration purposes, you can see that it is fully archived, not only for the type, method, and the nature of the file, but also for the structure, the election, the expansion, the Protocol and so on.
If you now have this app, we're starting to learn how to use Jazzy. First, in the terminal program, use thecdcommand to enter the item:
CD Path_to_project_folder
In the simplest case, you just need to enterJazzyand wait for Jazzy to complete its work. However, this does not contain any types or structures that are not useful for public decoration. If you want to include all of the things, you need to use this command:
Jazzy--min-acl Internal
In addition, if you do not have the latest version of Swift, you will not see the results of Jazzy, you can specify in the parameters a swift language version of the Xcode you are using:
Jazzy--swift-version 2.1.1--min-acl Internal
I strongly recommend that you usejazzy —helpthe command to browse through all the Jazzy parameters. You'll find that it has so much to do with these things that you can specify the way you want your Jazzy to work.
In the process of creating documents, you will see the following output in the console, which means that the files have been created.
The default output is the Docs folder under the item root (you can modify it).
Open the Docs catalog in the Finder and open the index.html page in the browser. You will immediately find that these documents are similar in style to the official Apple files. To click on some links in the page, try to jump through different pages and view the content displayed on the page. Now, use Jazzy in your own project!
Summary
It is necessary and important to file the code, but most of the members are not able to ignore it for the time being. When the deadline for the project is near delivery, it is not enough to fix the Bug, and it is difficult for us to compile the necessary files for each part of the code. But I want to pass through this article to make you aware of the importance of the document and to get the most out of editing the document's habits. You do not have to record all the details in your documents, but you should emphasize the important information in order to remind other developers, or to allow yourself to continue working on the base of the original code easily after a period of time. In addition, you can also create professional help files by Jazzy your password. This will greatly inspire our work desires. Write your documents happily in your code!
Translator's introduction
Yang Wang Yan, male, Chinese mainland people, CSDN Blog expert (personal blog http://blog.csdn.net/kmyhy). Started learning Apple IOS in 2009, proficient in the O-c/swift and Cocoa Touch framework, and developed multiple store applications and business apps. Passionate about writing, having and translating a number of technical expertise, including: "Enterprise-class IOS to Combat", "IPhone & IPad Business Mobility Tips", "IOS8 Swift Guide", "read to Busy People Swift" (co-translation), "ios Swift" Game development Cookbook "and so on.
Write a text file containing Mardown language for Swift code