Use Strings in Swift
Written by Team Kodeco
In Swift, a string is a sequence of characters, such as “Hello, World!”. You can create a new string by enclosing a sequence of characters in double quotes (””). Here’s an example of creating a new string:
let greeting: String = "Hello, World!"
The above example uses type annotation to manually specify the type of greeting as String
. Alternatively, it could have used type inference as follows:
let greeting = "Hello, World!"
print(type(of: greeting)) // Prints String
You can think of a string in Swift as a string of beads. Each bead represents a character in the string and you can add or remove beads to change the string.
String Interpolation
You can use string interpolation to include variables in a string, by placing them inside a pair of parentheses and preceded by a backslash.
let name = "John"
print("Hello, \(name)") //output: "Hello, John
Concatenating and Appending Strings
You can concatenate strings using the + operator or the += operator.
let firstName = "John"
let lastName = "Doe"
let fullName = firstName + " " + lastName // "John Doe
You can use the .append()
method to add a character or a string to an existing string.
var message = "Hello"
message.append(", World!")
print(message) // "Hello, World!"
Getting the Length of a String
You can also use the .count
property to get the number of characters in a string.
let message = "Hello, World!"
print(message.count) // output: 13