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

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.

主站蜘蛛池模板: 潞西市| 大悟县| 太原市| 温州市| 海门市| 永和县| 长海县| 行唐县| 图木舒克市| 呼伦贝尔市| 东乌珠穆沁旗| 巴马| 遵义市| 桦川县| 康马县| 嘉兴市| 田林县| 房产| 田阳县| 南郑县| 平和县| 龙川县| 万源市| 乌鲁木齐县| 宁远县| 淳化县| 刚察县| 门头沟区| 金坛市| 莆田市| 湘乡市| 惠来县| 图木舒克市| 叶城县| 临城县| 赤峰市| 伊金霍洛旗| 门头沟区| 拜城县| 靖西县| 屏南县|