Performing string operations

You can join two strings together using the '+' operator:

  1. Enter the following code and run it:
// you can concatenate two string using the '+' operator
let greeting = "Good" + " Morning"

The "Good" string is concatenated with the string " Morning", and "Good Morning" is displayed in the Results area.

You can combine strings with constants and variables of other types by casting them as strings.

  1. Enter the following code and run it:
// you can cast an integer or real as a string to concatenate it with another string
let rating = 3.5
var ratingResult = "The restaurant rating is " + String(rating)

The rating object contains 3.5, a value of type Double. Putting rating in String() converts the floating-point number into a string, "3.5", which is combined with the string in ratingResult, returning the string "The restaurant rating is 3.5".

There is a simpler way of combining strings though, called string interpolation. String interpolation is done by typing the name of a constant or variable between "(" and ")" in a string. 

  1. Enter the following code and run it:
// you can also use string interpolation
ratingResult = "The restaurant rating is (rating)"

As in the previous example, the value in rating is converted into a string, "3.5", returning the string "The restaurant rating is 3.5".

It is often very useful if you can display the contents of variables and constants to make sure your program is working as it should. In the next part, you'll see how to print stuff to the Debug area.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.157.142