Learn about Strings in Swift 5


PLEASE NOTE: This tutorial has been written using XCode 10 and Swift 5


String is a series of characters, such as "hello, world" or "flower". Swift strings are represented by the String type, and the contents of a String can be accessed in various ways, including as a collection of Character values.

Swift’s String and Character types provide a fast, Unicode-compliant way to work with text in your code. Despite this simplicity of syntax, Swift’s String type is a fast, modern string implementation. Every string is composed of encoding-independent Unicode characters and provides support for accessing those characters in various Unicode representations.

Initialize an Empty String

To create an empty String, either assign an empty string literal to a variable, or initialize a new String instance:

var myEmptyString = ""  // empty string
var anotherEmptyString = String()  // initializer syntax

NOTE: A variable can be changed in the code if it gets declared with the var prefix

You can check if a String is empty in this way:

if emptyString.isEmpty { 
    print("Nothing to see here")
// prints: "Nothing to see here"

String Literals

You can declare predefined String values within your code as string literals. A string literal is a sequence of characters surrounded by double quotation marks ("").

let myString = "Lorem ipsum dolor sit"

NOTE: A constant variable uses the let prefix and cannot be changed in the code.

You can also use a multiline string literal, it’s a sequence of characters surrounded by three double quotation marks:

let quotation = """
Lorem ipsum dolor sit amet, consectetur adipiscing: 
"elit, sed do eiusmod tempor incididunt", ut labore et dolore.

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip. 
"Duis aute irure dolor in reprehenderit", in voluptate velit esse cillum.

Here’s another example, where our string starts on the first line after the opening quotation marks (""") and ends on the line before the closing quotation marks. This means that neither of the strings below start or end with a line break:

let singleLineString = "These are the same."
let multilineString = """
These are the same.

To make a multiline string literal that begins or ends with a line feed, write a blank line as the first or last line:

let lineBreaks = """

Lorem ipsum dolor sit amet
consectetur adipiscing elit


Insert Special Characters in a String

A String can include the following special characters:

  • The escaped special characters  (null character), \ (backslash), t (horizontal tab), n (line feed), r (carriage return), " (double quotation mark) and ' (single quotation mark)
  • An arbitrary Unicode scalar value, written as u{n}, where n is a 1–8 digit hexadecimal number (Unicode is discussed in Unicode below)

The code below shows four examples of these special characters. The wiseWords constant contains two escaped double quotation marks. The dollarSignblackHeart, and sparklingHeart constants demonstrate the Unicode scalar format:

let wiseWords = ""Imagination is more important than knowledge" - Einstein"
// prints: "Imagination is more important than knowledge" - Einstein
let dollarSign = "u{24}"        // $,  Unicode scalar U+0024
let blackHeart = "u{2665}"      // ♥,  Unicode scalar U+2665
let sparklingHeart = "u{1F496}" // 💖, Unicode scalar U+1F496

Edit a String

You can edit a String by assigning it to a variable and append another string to it:

var variableString = "Hello"
variableString += " and welcome!"
// This produces: "Hello and welcome!"

let constantString = "Hello"
constantString += " and welcome!"
// This thorws a compile-time error - A constant string cannot be modified

Working with Characters

You can access the individual Character values for a String by iterating over the string with a for loop:

for myCharacter in "Hello!🐶" {
// H
// e
// l
// l
// o
// !
// 🐶

String values can also be constructed by passing an array of Character values as an argument to its initializer:

let myCharacters: [Character] = ["H", "e", "l", "l", "o"]
let myString = String(myCharacters)
// Prints: "Hello"

How to Concatenate Strings and Characters

String values can be added together (or concatenated) with the addition operator (+) or (+=) to create a new String value:

let string1 = "Hello"
let string2 = " there"
var welcome = string1 + string2
// "Hello there"

var string1 = "Hello"
string1 += string2
// string1 = "Hello there"

You may also append a Character to a String variable with the String type’s append()method:

let exclamationMark: Character = "!"
var string1 = "Hello"
// "Hello!"

NOTE: You can’t append a String or Character to an existing Character variable, because a Charactervalue must contain a single character only.

String Interpolation

String interpolation is a way to construct a new String value from a mix of constants, variables, literals, and expressions by including their values inside a string literal. You can use string interpolation in both single-line and multiline string literals. Each item that you insert into the string literal is wrapped in a pair of parentheses, prefixed by a backslash ():

let multiplier = 3
let message = "(multiplier) times 4 is (Double(multiplier) * 4)"
// "3 times 4 is 12"

How to Count Characters in a String

You can get the number of characters of a String in this way:

let myString = "hello world, how is it going?"
print("myString has (myString.count) characters")
// Prints: "myString has 30 characters"

Comparing Strings

Here’s an easy way to compare 2 strings:

let string1 = "Hello world!"
let sameString = "Hello world!"
if string1 == sameString {
    print("These two strings are equal")
// Prints: "These two strings are equal"

String Prefix and Suffix

You can check the prefix and suffix of a String in this way:

let myString = "Lorem ipsum dolor sit amet"
if myString.hasPrefix("Lorem") {
  print("myString has 'Lorem' prefix")
// prints: "myString has 'Lorem' prefix"

if myString.hasSuffix("amet") {
  print("myString has 'amet' suffix")
// prints: "myString has 'amet' suffix"

For more info about Swift Strings, check the official Documentation: https://docs.swift.org/swift-book/LanguageGuide/StringsAndCharacters.html


That’s all for this tutorial, you have learned a little bit about Strings in Swift.

Hope you enjoyed this article, feel free to post comments about it. 

Buy me a coffee - XScoder - thanks for your support
Your support will be highly appreciated 😉