Create and Modify Strings in Swift
Written by Team Kodeco
Strings in Swift are a collection of characters in a specific order. Strings are used to store and manipulate text.
String are value type in swift, meaning they are copied when they are assigned to a new variable or passed to a function.
Let’s review some of the most common operations you might want to do with Strings in Swift.
Creating a String
Here’s how to create a string in swift:
// Creating an empty string
var emptyString = ""
// Creating a string with a string literal
var greeting = "Hello, World!"
Get the Length of a String
You can get the length of a string with count
:
var greetingLength = greeting.count // 13
Using String Interpolation
You can use string interpolation to include the value of variables in a string:
let name = "Bob"
print("Hello, \(name)!")
// Output: "Hello, Bob!"
Concatenating Strings
You can concatenate strings together with the +
operator:
let firstName = "Bob"
let lastName = "Smith"
let fullName = firstName + " " + lastName
print(fullName)
// Output: "Bob Smith"
Appending Strings
You can append to a string with the +=
operator or with append
:
var name = "Bob"
name += " "
name.append("Smith")
print(name)
// Output: "Bob Smith"
The rest of this section of the cookbook will go into more detail about how to use Strings in Swift.