Printing a statment in Swift.

While editing in the playground we can see the current value on the variable on the results pane on the right. But we will want to output our own single row messages instead of single numeric values. To do this we use the “println() or print()“.  We can use this to print a bankspace, a message or a variable content. We would also want to print or create a compound message. In most programming language it is called as String Concatenation,and done by using a + operator. But in Swift we make use of a String Interpolation. It may sound complex but it is not.

String Interpolation:

This is done by the use of “\()” a backslash and a pair of parenthesis. This is used when we want to output a message with multiple values stored in variables and combining them as a single message. For example consider the following statement.

We want to display this value for the following set of variable values in place of the variable name.

To do this we use the “\()” in place of relevant places and replace it with the variables as shown below.

This will replace the value from the variables and form a sentence as follows.

This is string interpolation. We can use this directly in print statement and it will replace the given part of the String  as follows.

This will print the following output.

The output will be directly seen on the result panel of the playground.

Using Equations in String Interpolation:

But we are not limited to this only. We can also make use of equations in it. For example.

Here we have length and breath inferred Integer. Thus the multiplication of the two int is resultant into an Integer. Lets see what happnes if we use one as Floating point number and one as Int.

Here length is inferred as a Floating point number and breath is inferred as an Int. When we multiply them. Swift does not implicitly know whom to convert resulting into an error. By default a number with decimal is considered as type Double, As the compiler does not know if the Int is to be converted into Double or Double is to be converted into an int ,it throws an compile time error. This can be taken care of by using type conversion. This is done by converting the Int into a double by using “Double()”.

This will print the Answer as.

In the next Post we will learn about Control Flow in Swift.