Introduction to Swift Development Lesson 1: Strings

1. Introduction to Swift Development Lesson 1: Strings

1.1. Scope of This Tutorial

In this tutorial, we will focus on how to use the Swift String class. In general, knowing how to use strings in any programming language is essential for fundamental development tasks, such as displaying texts to a user. As a result, we will learn how to generate our own strings and how to combine strings. Furthermore, we will also come across certain methods that are useful regarding strings.

2. What is the Swift String Class

2.1. Definition

According to Apple, the Swift String class represents an ordered collection of characters. For example, the text “Hello Appshocker.com” is a string literal representing an ordered collection of these characters (meaning its letters). By “ordered collection,” it is meant that the sequence of the characters of the word “hello” is ordered, because “h” comes first, “e” comes second, “l” comes third, and so on. This means that we have a tool (meaning this Swift String class) to use a collection of letters, the string.

2.2. Simple Example

A very simple example of a Swift string is the following:

var myFirstString = "Hello Appshocker.com"

Equally correct is the case if you do not use type inference, meaning specifying the type of the var “myFirstString,” such as:

var myFirstString:String = "Hello Appshocker.com"

For the sake of simplicity, we will not be specifying the type of a variable in the upcoming examples for this tutorial.

Therefore, in order to use a simple string, you need this:

  • Use either a “var” or a “let” in order to create a string variable or string constant, meaning “var aStringVariable” or “let aStringConstant.” However, due to simplicity reasons, we will focus on string variables in this tutorial.
  • Name a string literal representing the string text. In this case, it is “myFirstString”
  • An equal sign assigning the string literal to a specific string.
  • The actual string placed within “” (meaning the inverted commas). In this case, it is “Hello Appshocker.com”.

3. How to Use the Swift String Class

3.1. Creating an Empty String

The simplest way of how to create an empty string is the following:

var myEmptyString = ""

The variable “myEmptyString” is simply an empty string not containing any characters whatsoever; however, bear in mind you did create a string instance.

Another way is the following:

var initializingAnEmptyString = String()

Both are equal in the sense that you create the same empty string. In order to verify this, please see the following Playground image:

swift_empty_string

3.2. Creating a Filled String

The simplest way of how to create a filled string is the following:

var myFilledString = "Hi"

As you can see, the variable “myFilledString” contains the simple string literal “Hi”.

Another way to create the same result is the following:

var anotherFilledString = String("Hello")

Both are equal in the sense that you create the same filled string. In order to verify this, please see the following Playground image:

swift_filled_string

3.3. Concatenating Strings

3.3.1. Using \() aka String Interpolation

In your future Swift projects, you will highly likely come across the situation where you will be having to combine two strings so that you create a new one.
Hence, let us assume we would like to use the following two strings to do this:

var myFirstString  = "Hello Appshocker.com"

var mySecondString = "I like your tutorials"

Now, Swift provides us with the following mechanism to combine these two strings:

\()

This symbol is a reference to a specific variable, in this case, a string variable. Therefore, in order to use it with our strings, we need to write the following:

var myFirstString  = "Hello Appshocker.com"

var mySecondString = "I like your tutorials"

var theCombinedString = "\(myFirstString) \(mySecondString)"

The result of the third string variable “theCombinedString” is “”Hello Appshocker.com I like your tutorials.” See the result from the Swift Playground:

swift strings combination

3.3.2. Using the .stringByAppendingString() Method

Here, we will use the same two strings used prior to the example above. However, we will use a method provided by the Swift String class, namely “.stringByAppendingString()”:

var myFirstString  = "Hello Appshocker.com"

var mySecondString = "I like your tutorials"

myFirstString.stringByAppendingString(mySecondString)

The result will be the same as in the previous case. See the Swift playground for proving this:

swift_string_stringbyappendingstring

As you can see, we did not need any third string variable. We could retrieve the same result only by applying the method “.stringByAppendingString()” on the “myFirstString” variable. Therefore, bear in mind that the string variable “myFirstString” was initially filled with the string “Hello Appshocker.com”. However, by applying this method, this string variable “myFirstString” was modified with the content of the string variable “mySecondString.” In other words, the initial content of your first string variable was extended with the text from the second string so that we can combine the content of both string variables in one string variable.

3.3.3. Using the += Operator

Apart from the previous two ways to concatenate strings, Swift also offers a third option: the += (addition assignment) operator.
Let us take a closer look at the following code:

var mySecondString = " I like your tutorials"

var myFirstString  = "Hello Appshocker.com"

myFirstString += mySecondString

The result will be the same as in the previous case. See the Swift playground for proving this:

swift_concatenating_addition_assignment_operator

As illustrated above, we did not require any third variable either. We simply used the first variable with the “+=” operator in combination with the second string variable. By this, we added the content of the second string variable to the first one so that the first one now contains the content of both variables.

3.3.4. Using the + Operator

Morever, Swift also offers the following mechanism:

var myFirstString  = "Hello Appshocker.com"

var mySecondString = " I like your tutorials"

var myThirdString  = myFirstString + mySecondString

The result will be the same as in the previous case. See the Swift playground for proving this:

swift_concatenating_addition_assignment_operator

3.3.5. Using the String Format Specifier

Furthermore, Swift provides us with another quite helpful mechanism, the String Format Specifier. In this tutorial, we will only focus on the string and integer specifier. You can look up all specifiers provided on Apple’s website, see https://developer.apple.com/library/ios/documentation/cocoa/conceptual/Strings/Articles/formatSpecifiers.html.

var myFirstString  = "Hello Appshocker.com"

var mySecondString = " I like your tutorials"

var myThirdString  = String(format: "Combining these: %@ and %@", myFirstString, mySecondString)

The result will be the same as in the previous case. See the Swift playground for proving this:

swift_concatenating_addition_assignment_operator


Personal opinion:
Just a tip from my working experience: in the past few years, during the time when Objective-C was the primary programming language for iOS (ignoring C/C++ in this case), I have been using this way of creating new strings, namely with a String Format Specifier, literally on a regular basis. The reason why I have been doing that is the fact that you can substitute the string variables placed by the operating system for the different “%@” relatively easily. For example, if you intend to use “string2” at the place of %@ where you currently use “string1,” then you simply have to remove the previous string variable in a second and you are done. In the other cases, you can also do this with the other concatenation mechanisms; however, in the case of Swift, time will tell which one will be more beneficial for my work. I will keep you updated on my personal experience regarding this topic.

3.5. Other Useful Methods

3.5.1. The Length of a String

During the development of your Swift project, you will need to know how many characters a string actually contains. In order to find this out, Swift provides a method called “.utf16count”. This method returns an integer indicating the amount of characters within a given string:

var myFirstString  = "Hello Appshocker.com"

myFirstString.utf16Count

See the Swift Playground for proving the result:

swift_string_utf16count

Attila Alexander Teglas has written 58 articles

Attila is a freelance software architect, project manager, consultant, and instructor with more than eight years of experience in the software industry. He developed and managed projects for elite universities, medium-sized companies, multi-national corporations, and the European Union.

He has been developing mobile applications, primarily iOS and Android, for more than five years.

Furthermore, he conducted more than 150+ architecture reviews and audits of mobile apps, scrutinizing and detecting issues & defects for the improvement of these projects.

Regularly, he lectures iOS and Android development to computer science students. Attila rejoices teaching the possibilities and pitfalls of iOS and Android development, giving students the skillset to develop their own high quality apps.

While not writing apps, Attila improves his Chinese and Russian language skills and he travels the world with his beautiful wife.