Skip to main content

Swift Strings Basics

Introduction

Strings are one of the most fundamental data types in programming, representing sequences of characters like text, names, or any other textual content. In Swift, strings are represented by the String type, which is a powerful and Unicode-compliant implementation.

This guide will walk you through the basics of working with strings in Swift, from creation to common operations that you'll use in everyday programming.

Creating Strings in Swift

Swift provides several ways to create and initialize strings.

String Literals

The most common way to create a string is using a string literal, which is text enclosed in double quotation marks:

swift
let greeting = "Hello, world!"

Empty Strings

You can create an empty string in two ways:

swift
// Method 1: Using an empty string literal
let emptyString = ""

// Method 2: Using the String initializer
let anotherEmptyString = String()

// Both strings are empty
print(emptyString.isEmpty) // Output: true
print(anotherEmptyString.isEmpty) // Output: true

Multiline Strings

For text that spans multiple lines, Swift offers multiline string literals using three double quotation marks:

swift
let poem = """
Roses are red,
Violets are blue,
Swift is awesome,
And so are you!
"""
print(poem)
/* Output:
Roses are red,
Violets are blue,
Swift is awesome,
And so are you!
*/

String Concatenation

You can combine strings using the addition operator (+) or the append method:

swift
// Using the + operator
let firstName = "John"
let lastName = "Doe"
let fullName = firstName + " " + lastName
print(fullName) // Output: John Doe

// Using the += operator
var message = "Hello"
message += ", " + firstName
print(message) // Output: Hello, John

// Using the append() method
var greeting = "Welcome"
greeting.append(" to Swift")
print(greeting) // Output: Welcome to Swift

String Interpolation

String interpolation is a way to construct a string by including variables, constants, expressions, and function calls within a string literal. In Swift, you use \(expression) syntax:

swift
let name = "Alice"
let age = 28
let message = "Hello, my name is \(name) and I am \(age) years old."
print(message) // Output: Hello, my name is Alice and I am 28 years old.

// You can also include expressions
let a = 5
let b = 10
print("The sum of \(a) and \(b) is \(a + b)") // Output: The sum of 5 and 10 is 15

String Properties and Methods

Character Count

To get the length of a string (number of characters):

swift
let message = "Swift is fun!"
print(message.count) // Output: 13

Checking if a String is Empty

swift
let emptyString = ""
let nonEmptyString = "Hello"

print(emptyString.isEmpty) // Output: true
print(nonEmptyString.isEmpty) // Output: false

Case Conversion

Swift provides methods to change the case of strings:

swift
let original = "Swift Programming"

// Convert to uppercase
let uppercased = original.uppercased()
print(uppercased) // Output: SWIFT PROGRAMMING

// Convert to lowercase
let lowercased = original.lowercased()
print(lowercased) // Output: swift programming

// Capitalize the first letter of each word
let capitalized = original.capitalized
print(capitalized) // Output: Swift Programming

Checking Prefixes and Suffixes

swift
let message = "Swift is amazing!"

// Check prefix
let hasSwiftPrefix = message.hasPrefix("Swift")
print(hasSwiftPrefix) // Output: true

// Check suffix
let hasExclamationSuffix = message.hasSuffix("!")
print(hasExclamationSuffix) // Output: true

Comparing Strings

You can compare strings using the standard comparison operators:

swift
let string1 = "apple"
let string2 = "banana"
let string3 = "apple"

// Equal to
print(string1 == string3) // Output: true

// Not equal to
print(string1 != string2) // Output: true

// Greater than
print(string2 > string1) // Output: true (alphabetically, "banana" comes after "apple")

Real-World Examples

Creating a User Greeting

swift
func createGreeting(for username: String, timeOfDay: String) -> String {
return "Good \(timeOfDay), \(username)! Welcome back."
}

let greeting = createGreeting(for: "Sarah", timeOfDay: "morning")
print(greeting) // Output: Good morning, Sarah! Welcome back.

Building a URL String

swift
func buildAPIURL(baseURL: String, endpoint: String, parameters: [String: String]) -> String {
var url = baseURL
if !url.hasSuffix("/") {
url.append("/")
}

url.append(endpoint)

if !parameters.isEmpty {
url.append("?")
var isFirst = true

for (key, value) in parameters {
if !isFirst {
url.append("&")
}
url.append("\(key)=\(value)")
isFirst = false
}
}

return url
}

let apiURL = buildAPIURL(
baseURL: "https://api.example.com",
endpoint: "users",
parameters: ["limit": "10", "sort": "desc"]
)
print(apiURL) // Output: https://api.example.com/users?limit=10&sort=desc

Simple Text Processing

swift
func countWords(in text: String) -> Int {
let trimmedText = text.trimmingCharacters(in: .whitespacesAndNewlines)
if trimmedText.isEmpty {
return 0
}

let words = trimmedText.components(separatedBy: .whitespaces)
return words.filter { !$0.isEmpty }.count
}

let sentence = "Swift is a powerful programming language!"
print("Word count: \(countWords(in: sentence))") // Output: Word count: 6

Summary

In this guide, we've covered the basics of working with strings in Swift:

  • Creating strings using literals, initializers, and multiline syntax
  • Concatenating strings using various methods
  • Using string interpolation to embed values in strings
  • Working with string properties and methods like count and isEmpty
  • Manipulating strings with case conversion
  • Checking prefixes and suffixes
  • Comparing strings
  • Real-world applications of Swift strings

Strings are versatile and essential for almost any app you'll build, from displaying text on the screen to processing user input and building network requests.

Exercises

To strengthen your understanding of Swift strings, try these exercises:

  1. Write a function that reverses a string without using the built-in reversed() method.
  2. Create a function that checks if a string is a palindrome (reads the same backward as forward).
  3. Implement a function that counts the occurrences of a specific character in a string.
  4. Build a simple text formatter that converts snake_case to camelCase (e.g., "user_name" becomes "userName").
  5. Write a function that censors specific words in a text by replacing them with asterisks.

Additional Resources



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)