官术网_书友最值得收藏!

  • Learning Swift
  • Andrew J Wagner
  • 310字
  • 2021-07-16 13:54:08

Printing on the console

It can be very useful to write output to a log so that you can trace the behavior of some code. As a code base grows in complexity, it can be hard to reason about the order in which things happen and exactly what the data looks like as it flows through the code. Playgrounds can help a lot with this, but this is not always enough.

In Swift, this process is called printing to the console. To do this, you use something called println, which is short for print line. It is used by writing println followed by some text surrounded by parenthesis. For example, to print Hello World! to the console, the code would look like this:

println("Hello World!")

If you put that code into a playground, you will see "Hello World!" written in the results pane. However, this is not truly the console. To view the console, you can go to View | Assistant Editor | Assistant Editor. A new view will appear to the right of the results pane and it will have a section called Console Output that will include all the text the code has printed to the console.

Printing on the console

Not only can you print static text to the console, you can also print any variable. For example, if you wanted to print the name variable, you would write:

println(name)   

You can even use a feature of Swift called string interpolation to insert variables into a string:

println("Hello \(name)!")

At any point in a string literal, even when you're not printing, you can insert the results of code by surrounding the code with \ (and). Normally, this will simply be the name of a variable, but it can be any code that returns a value.

Printing to the console will become even more useful as we start using more complex code.

主站蜘蛛池模板: 泰来县| 安乡县| 通江县| 淮北市| 福建省| 甘谷县| 乐山市| 奇台县| 新晃| 左云县| 友谊县| 景洪市| 工布江达县| 黄山市| 清苑县| 平果县| 缙云县| 邻水| 河津市| 武穴市| 曲阳县| 呼伦贝尔市| 得荣县| 无极县| 宝应县| 郧西县| 松潘县| 河源市| 仁布县| 京山县| 荆州市| 郯城县| 永丰县| 东台市| 遂宁市| 双峰县| 临邑县| 西藏| 泾源县| 吴川市| 辛集市|