Swift Strings and Characters

by Dimitris Tasios
7 views

In this article, we’ll learn how to use Strings and Characters in Swift, through multiple examples.

1. Swift Characters

In Swift, a Character is a data type that represents a single Unicode symbol. This symbol can be a letter, a number, or even an emoji.

In order to create a Character variable, we have to explicitly declare it as a Character and enclose its value in double quotation marks (""). If we do not declare it as a Character, Swift will automatically declare as a String instead.

Lastly, only a single symbol is allowed to be allocated to a Character variable. If we try to allocate 2 characters or more, we’ll get a compile-time error.

You can see all of the above in action, in the snippet below:

let letterD: Character = "D" // type: Character
let smirkEmoji: Character = "😏"  // also a valid Character
let stringD = "D" // by default, this is a String

// Invalid Character
let invalidCharacter: Character = "Hello" // compile-time error: Character must only have one character

The vast majority of times, we will need to work on more than one character at a time. In other words, Character on its own doesn’t offer us much. That’s when String comes into play.

2. Swift Strings

String is a data type that represents an array of Character values. In other words, a String represents actual words, sentences, and even paragraphs.

In order to create a String, we have to enclose it in double quotation marks (""). We don’t have to declare its type, since Swift will automatically do that for us, through type inference.

let helloWorld = "Hello world!" // automatically inferred as a String
let anotherHelloWorld: String = "Hello world!" // explicitly declared as a String

In the following sections, we’ll examine various topics surrounding String and move on to a few operations that we can use on String.

2.1 Multi-line Strings in Swift

A String can be declared in one or multiple lines. If we want to achieve the latter, we have to use 3 quotation marks (""") and write our message on the next line. If we try starting our message on the same line as the quotation marks, we’ll get a compile-time error.

let multilineString = """
This
message
spans
in
multiple
lines
"""

print(multilineString)

The output is:

This
message
spans
in
multiple
lines

2.2 Escaping Characters in a String

As you might have noticed, the quotation marks are not printed. If we try to have a String like the following, we’ll get a compilation error.

let notEscapedIntroduction = "My name is "Dimitris""

Whenever Swift looks at the aforementioned String, it will read it as two strings; My name is and an empty String, ignoring Dimitris. This happens because the quotation marks are special characters in Strings that are essential to creating Strings.

In order to include them in a String, along with other special characters, we have to escape them. Escaping is done by preceding the special character with a backslash (\). So, the following correction to our aforementioned String will work as intended:

let introduction = "My name is \"Dimitris\""
print(introduction)

The output is:

My name is "Dimitris"

As you might have thought, the backslash itself is a special character, so in order to use it as a character in a String, we have to escape it as well. Here’s an example that includes all the special characters that we must escape in order to use them in Strings:

Special CharacterDescription
\0null character
\”quotation mark
\\backslash
\ttab
\nnew line
Figure 1. List of special characters that need escaping.
let doubleQuotationMark = "Double quotation mark: \"Terremoto\" is Spanish means \"Earthquake\"."
let nullCharacter = "Null: \0"
let backslash = "Backslash: To escape a character, we have to preceed it with a backslash (\\)."
let newLine = "New line: Article Title: Swift Strings and Characters \nWritten by: Dimitris Tasios"
let tab = "Tab: Article Title: Swift Strings and Characters \n\tWritten by: Dimitris Tasios"

print(doubleQuotationMark)
print(nullCharacter)
print(backslash)
print(newLine)
print(tab)

The output is:

Double quotation mark: "Terremoto" is Spanish means "Earthquake".
Null: 
Backslash: To escape a character, we have to preceed it with a backslash (\).
New line: Article Title: Swift Strings and Characters 
Written by: Dimitris Tasios
Tab: Article Title: Swift Strings and Characters 
	Written by: Dimitris Tasios

2.3 String Interpolation

In case we want to include a variable inside a String, the cleanest and quickest way to do it is by using String Interpolation. In order to do that, we surround our variable in brackets, which are then preceded by a backslash (\).

let siteName = "Code Learn Hub"
let siteIntroduction = "This example was written for the website \(siteName)."
print(siteIntroduction)

The output is:

This example was written for the website Code Learn Hub.

There is also another way to include a variable within a String, which requires appending our variable in the String. We’ll see that shortly.

3. String Operations

There are many operations we can use on a String. In this section, we’ll see the most common ones.

3.1 Checking the Length of a String

As we’ve mentioned, a String is an array of characters, so all operations available for arrays are also available for Strings.

In order to check the length of a String, we use the count property, available to all arrays. Additionally, we can check whether the String is empty, with the isEmpty property.

let laser = "Light Amplification by Stimulated Emission of Radiation"
print(laser.count)      // 55
print(laser.isEmpty)    // false

let crickets = ""
print(crickets.count)   // 0
print(crickets.isEmpty) // true

3.2 String Comparison

Unlike other programming languages, comparing Strings in Swift is simple, by the == operator. On the other hand, checking that two Strings are unequal is done by the != operator.

let languageOfArgentina = "Spanish"
let languageOfMexico = "Spanish"
let languageOfBrasil = "Portuguese"

print(languageOfArgentina == languageOfMexico) // true
print(languageOfArgentina != languageOfMexico) // false

print(languageOfArgentina == languageOfBrasil) // false
print(languageOfArgentina != languageOfBrasil) // true

3.3 Appending and Concatenating Strings

As long as our String is a variable and not a constant, we can append more Strings to it. This can be done with the append() function, found in all arrays. Using append() on a constant String will generate a compile-time error.

var myNameIsSticker = "Hi! My name is "
myNameIsSticker.append("What?")
print(myNameIsSticker) // Hi! My name is What?

// the following cannot be done
let anotherMyNameIsSticker = "Hi! My name is "
anotherMyNameIsSticker.append("Who?") // compile-time error

Additionally, we can use the + and += operators to concatenate Strings together, like so:

let plants = "plants"
let birds = "birds"
let rocks = "rocks"
var desert = "There were " + plants + " and \(birds) and "
desert += rocks
desert.append(" and things")
print(desert)

The output is:

There were plants and birds and rocks and things

In the example above, we have used all the ways we can unite Strings together:

  • For the plants constant, we have used the + operator on either side of it.
  • Then, we have used String interpolation for birds, as seen before.
  • Rocks uses the += operator.
  • Lastly, the literal “ and things” uses the append() function.

3.4 Converting a String to Uppercase and Lowercase

We can convert a String to both uppercase and lowercase, by using the uppercased() and lowercased() functions respectively.

let clh = "Code Learn Hub"
print(clh.uppercased()) // CODE LEARN HUB
print(clh.lowercased()) // code learn hub

3.5 Checking for Prefix and Suffix

The last String operations we will see in this article are the hasPrefix() and hasSuffix() functions. The former function checks whether a String starts with a given String, while the latter checks if a String ends with a given String.

let favouriteAlbum = "How I Spent My Summer Vacation"
print(favouriteAlbum.hasPrefix("How I Sp"))     // true
print(favouriteAlbum.hasPrefix("Summer"))       // false

print(favouriteAlbum.hasSuffix(" Vacation"))    // true
print(favouriteAlbum.hasSuffix(" Spent "))      // false

4. Conclusion

By now, you should be able to use Characters and Strings in Swift without any problem. You can find the source code (Playground) on our GitHub page.

Related Posts