- Learning Swift(Second Edition)
- Andrew J Wagner
- 291字
- 2021-07-16 12:33:06
Printing to the console
It is very useful to write output to a log so that you can trace the behavior of code. As a codebase grows in complexity, it gets hard to follow the order in which things happen and exactly what the data looks like as it flows through the code. Playgrounds help a lot with this but it is not always enough.
In Swift, this process is called printing to the console. To do this, you use something called print. It is used by writing print followed by text surrounded by parentheses. For example, to print Hello World! to the console, the code would look like this:
print("Hello World!")
If you put that code in a playground, you would see Hello World! written in the results pane. However, this is not truly the console. To view the console, you can go to View | Debug Area | Show Debug Area. A new view will appear at the bottom of the window and it will contain all text the code has printed to the console:

Not only can you print static text to the console, you can also print out any variable. For example, if you wanted to print out the name variable, you would write:
print(name)
You can even use a feature of Swift called string interpolation to insert variables into a string, like this:
print("Hello \(name)!")
At any point in a string literal, even when not printing, you can insert the results of the code by surrounding the code with \( and ). Normally this would be the name of a variable but it could be any code that returns a value.
Printing to the console is even more useful when we start using more complex code.
- Hands-On Industrial Internet of Things
- 走進物聯(lián)網(wǎng)
- 計算機網(wǎng)絡與通信(第2版)
- 企業(yè)網(wǎng)絡安全管理
- OMNeT++與網(wǎng)絡仿真
- The Kubernetes Workshop
- 網(wǎng)絡利他行為研究:積極心理學的視角
- Getting Started with Memcached
- Hands-On Bitcoin Programming with Python
- Guide to NoSQL with Azure Cosmos DB
- 商業(yè)的本質和互聯(lián)網(wǎng)
- 智慧城市中的物聯(lián)網(wǎng)技術
- 新IP:面向泛在全場景的未來數(shù)據(jù)網(wǎng)絡
- Architecting Data:Intensive Applications
- 通信系統(tǒng)實戰(zhàn)筆記:無處不在的信號處理