Swift String Basics and String Interpolation

In this article, we'll go over the basics of Swift Strings and how to use String Interpolation.

Creating Strings

In Swift, any text wrapped in double quotes (") is considered a string.

You can create string variables and constants like this.

var s1 = "This is a string variable"
let s2 = "This is a string constant"

The above works for single-line strings. To define multi-line strings, wrap the text with three double quotes on separate lines.

let s = """
This way,
you can define
a multi-line string.
"""
print(s)

The output looks like this.

This way,
you can define
a multi-line string.

Checking if a String is Empty

To check whether a string is empty in Swift, use the isEmpty property.

var s = ""
print(s.isEmpty)

s = "Test"
print(s.isEmpty)

The output shows that isEmpty returns true when the string is empty.

true
false

Getting String Length

To get the length of a string in Swift, use the count property.

var s = ""
print(s.count)

s = "Test"
print(s.count)

s = "😊"
print(s.count)

The output is.

0
4
1

Depending on the character, the "length" may differ depending on how it's encoded. If you need to check using character encodings, you can convert a string to unicodeScalars, utf8, or utf16 and then use count on them.

let s = "😊"
print(s.count)
print(s.unicodeScalars.count)
print(s.utf8.count)
print(s.utf16.count)

The output looks like this.

1
1
4
2

Using String Interpolation

String Interpolation makes it easy to generate strings from variables and expressions. It's a convenient feature that's used frequently when programming in Swift.


To include variables or expressions inside a string, wrap them with \( ).

let name = "Emily"
let s1 = "Hello, \(name)!"
print(s1)

let value = 5
let s2 = "\(value) + 2 is \(value + 2)."
print(s2)

The output shows that expressions inside \( ) are evaluated and converted into strings.

Hello, Emily!
5 + 2 is 7.

That's it for the basics of Swift Strings and String Interpolation.