Lesson 8Swift Basics
Strings
Strings in Swift
Strings are sequences of characters used to store text. Swift makes working with strings easy and powerful!
Creating Strings
- Use double quotes:
"Hello" - Join with
+ - Multi-line with
"""
Useful String Properties
.countNumber of characters
.isEmptyCheck if empty
.uppercased()Convert to uppercase
.lowercased()Convert to lowercase
String Methods
.hasPrefix()Starts with?
.hasSuffix()Ends with?
.contains()Contains?
main.swift
// Creating strings
let greeting = "Hello"
let name = "Swift"
// Concatenation (joining strings)
let message = greeting + ", " + name + "!"
print(message) // Hello, Swift!
// String interpolation (inserting values)
print("\(greeting), \(name)!")
// Multi-line strings
let poem = """
Roses are red,
Violets are blue,
Swift is awesome,
And so are you!
"""
print(poem)
// String properties
let text = "Hello, World!"
print(text.count) // 13 (character count)
print(text.isEmpty) // false
print(text.uppercased()) // HELLO, WORLD!
print(text.lowercased()) // hello, world!
// String methods
print(text.hasPrefix("Hello")) // true
print(text.hasSuffix("!")) // true
print(text.contains("World")) // true
// Loop through characters
for char in "Swift" {
print(char)
}Try It Yourself!
Create a greeting message with your name and print it in uppercase and lowercase!