Swift Tutorial 3 – How to Use Strings in Swift

We’ve looked at mostly numerical types and data in the past, but, in this post, we’re going to be looking at character data. A string is a sequence of characters. That’s why it’s called a string: it’s a “string” of characters!

We can create string constants and variables by enclosing the characters in double-quotes: let greeting = "Hello!" . If we want to create an empty string, we can either use two consecutive double-quotes, or we can use Swift’s initializer syntax. We can also check if a string is empty by using a property that all strings have called isEmpty.

String Mutability

We can alter, or mutate, our strings, but we need to be careful as to what is a constant and what isn’t. From previous parts, we know we can use the addition operator as the string concatenation operator. We can also use the compound addition (+=) operator to tack on a string to the current string, unless the current string is a constant!

Since the second string is a constant, we can’t append to it! However, we could still use it to create other strings: var greeting = immutableGreeting + "world!".

String Interpolation

Suppose we had some number values that we wanted to insert into a string. We can use Swift’s string interpolation to directly insert other variables into a string.

In the above code snippet, we declare two variables, one to be the cost of an item and another to be the tax on that item. We can craft a string that contains those values along with the total cost of the item. The syntax for string interpolation is to put a backslash and the variable or value of expression we want to insert in parentheses after the backslash. Note that the first two interpolations are variables only, but the last one is actually an expression. Swift calculates the value of that expression and then inserts that value into the string.

Characters

As we know from our definition of string, characters make up strings. We can gain access to all of the characters of a string to count them using the characters property.

We can access the characters property on any string, then access the count property of those characters and get the length of any string. We can even use a for-in loop (discussed more in control flow) to iterate through all of the characters of a string using the same characters property.

We’re using the print function to print the output to the right pane. Clicking on the preview icon in the variable pane might only show the last output. We can right-click on the popup window and select “Value History” to see all of the output of the print statement. As mentioned, we’ll see more of the for-in loop when we get to control flow, but the loop allows us to iterate through all elements of a collection type.

Accessing Characters in Strings

Now that we know of various methods of combining strings, we can learn how to access the characters of a string and perform more complicated operations such as inserting or deleting characters. String are what we call indexed. This means that we can use square brackets to access a particular character of the string. However, we can’t use integer positions like zero, one, or two, since Swift strings can contain Unicode characters of varying memory length. We need to use Swift’s built-in properties and functions to get particular characters from a string.

In the above code snippet, we’re using Swift’s built-in startIndex, endIndex, and index method to access the string. The second line of code retrieves the first character, which is located at the string’s startIndex. The next line retrieves the string’s last character. The value of the string at endIndex is not the last character!!! The first character is at zeroth index and the last character is at the end minus one. In memory, the absolute last character is the null character to help your operating system figure out when the string ends and another variable’s memory begins. We can’t directly use integers to get the last index minus one so we can use the   index(...)  method to access a character before and index, after an index, or offset from an index. The fourth line will return the second character in the string. The final line will return the third character in the string since we start at the first character and move forward two characters. In general, take whatever x is in the index(..., offsetBy: x)  function, add one to it, and that is the position of the character.

Earlier, we saw how we can use the for-in loop to iterate through all of the characters, but there’s another way we can do this.

Instead of iterating through the characters themselves, we can iterate through the indices! This will print out all of the characters in “Hello”. We won’t have to check the index variable since we’re using it in a for-in loop so we’re guaranteed that all of the indices we iterate over will be valid, and we can use them in the square bracket notation.

Modifying Characters in Strings

We’ve looked at how we can retrieve characters, but suppose we want to modify characters in a string. We’re going to see how we can insert and delete characters from a string. For example, we can insert a character at a particular index using an insert function.

Notice how this function has a named parameter “at:”. We’ll talk more about functions later, but this is a way we can differentiate our input parameters. This function will insert the given character at the index before the given one. It’s ok to pass endIndex since the new character will be inserted between the last accessible character and endIndex , which is at the very end after the “o”.  It’s also important to note that this only inserts characters and not entire strings. To insert entire strings, we can use the same function, but with a named parameter  contentsOf: as the first input.

This function can insert the characters in of string right before the given index, similar to the other  insert(...)  function. Now let’s look at how we can remove characters from a string. Similar to how we can insert a character at a specific index, we can analogously delete a character at an index.

The removeAtIndex(...)  will delete the character at the given index and return the deleted character. To see the results, we need to type the variable after deleting a character so that the right-pane will update with the new string. Similar to inserting multiple characters at an index, we can also delete a range of characters.

To define the range, we need to use the range operators we learned about. This example also illustrates how we can retreat from the end of a string. The character 5 steps backwards from the end is the space. We go up to, but not including, the last character, the exclamation point. This will remove everything from the space to the end of “Bob”. If we wanted to remove the exclamation point as well, we would have to go up to, but not including endIndex.

String Comparison

We can check for pure string equality in a similar fashion to numbers: using the equality operator (==). This will do a character-by-character check of the string. This includes whitespace!

Instead of checking for pure equality, we can check for prefix and suffix equality as well. The way this works is Swift will check the number of characters at the beginning or end depending on the length of the string we pass into the hasSuffix(...)  or hasPrefix(...)  functions.

The longer the parameters to the function, the more characters that Swift checks in the query string. Prefixes are checked iterating forward and suffixes are checked iterating backwards.

To review, in this section, we learned all about strings and characters. We first learned how to create a string or an empty string. Then we learned how to modify strings using the compound plus operator (+=). We then covered how to insert variables into a string using string interpolation. Characters were discussed next. Finally, we ended with string modifications and comparisons.

Published by

Mohit Deshpande

Mohit Deshpande is a professional mobile application developer, contractor, and instructor. He started programming at the age of eleven. During the great mobile revolution, he shifted focus to developing mobile apps with his first Android app running on a Samsung Galaxy S1 running Android 2.1 Eclair. Since then, he has been involved in industry and research. He is a computer science and engineering student at The Ohio State University and works for the Department of Computer Science and Engineering as a researcher. During the university hackathon, he came in second place with an Android app that links a task with a location using a geofence. In what little spare time he has, he plays jazz and rock guitar and performs in the Ohio State Athletic Band on trumpet at various sporting events.

Share this article

Leave a Reply

avatar
  Subscribe  
Notify of