iOS Development #8: Strings

iOS Development #8: Strings
Jan Zavrel
Jan Zavrel Follow June 27, 2021

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:

name = "Jan"

You should see the number of characters in your name display in the Console:

Counting the number of characters in your name

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:


Modifying string with 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.

String Interpolation

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("My age is: \(age).")
print("My name has \(name.count) characters.")

This is how your code should look like now:

String interpolation

Follow me on Medium, Twitter, Facebook and YouTube.

Jan Zavrel
Written by

Jan Zavrel Follow

Developer, Author, Teacher, Evernote Certified Consultant.