Swift Strings

Swift Strings

A String is a series of characters, such as "Hello, World!".

Swift strings are fast, modern, and provide a wide variety of tools for text manipulation.

Strings in Swift are Unicode-compliant, meaning they fully support emojis and international characters!


Creating Strings

You can create a string by enclosing text in double quotation marks "".

Creating Strings:

let greeting = "Hello, Swift!"
var emptyString = ""
print(greeting)

Multi-Line Strings

If you need a string that spans multiple lines, enclose the text in three double quotation marks """.

Multi-Line String:

let poem = """
The woods are lovely, dark and deep,
But I have promises to keep,
And miles to go before I sleep.
"""
print(poem)

String Concatenation

You can add (concatenate) two strings together using the addition operator +.

Concatenation Example:

let firstName = "John"
let lastName = "Doe"
let fullName = firstName + " " + lastName
print(fullName)

String Properties and Methods

Swift strings come with built-in properties and methods that are highly useful.

For instance, you can count the number of characters in a string using the .count property.

You can also convert a string to uppercase using the .uppercased() method.

String Properties:

let word = "Intricate"
print("Length: \(word.count)")
print("Uppercase: \(word.uppercased())")

Exercise

How do you define a multi-line string literal in Swift?