String is another important and useful data type. It’s also a struct like Int but String gives us much more functionality.
Strings are always wrapped with quotes, preferably double quotes ("...").
Since String is actually a group of individual characters, we can count those characters.
Let’s say I want to store the value “Jan” (which is my name), to the variable and then I want to find out how many characters there are in my name. We already declared the name variable in the previous article, so we can just initialize it now with a value.
Write this code with your own name to the Playground and run it:
You should see the number of characters in your name display in the Console:
The count is an example of a struct’s property. Property is something that describes the specific value stored in the struct. But structs have also methods, special functions that can modify the stored values.
We can for example change the case of letters by using the uppercased() method:
Notice how we access both properties and methods of the struct by using the dot in front of their names. This is called a dot notation.
So far, we printed just the value of the variable, but as you can see from the output in the Console, it’s already quite hard to track what different numbers represent.
String interpolation allows us to insert a value directly into a string. To do this, we need to write use a backslash \ follow by the value in parentheses ().
Let’s rewrite our code with string interpolation so we know exactly what each value in the Console represents:
..//print(age)print("My age is: \(age).")..//print(name.count)print("My name has \(name.count) characters.")