Understanding Swift - Strings


Strings in Swift are an ordered collection of characters, commonly used to store and manipulate text. They are represented by the String data type, which allows developers to handle textual information efficiently.

How to Create a String in Swift

In Swift, you can create a string in two ways:


1. Using String Literals

2. Using the String Class

Syntax & Examples

1. Using String Literals

A string literal is the easiest way to define a string in Swift:

var str = "Hello, Swift!"
var str: String = "Hello, Swift!"

2. Using the String Class

You can also create a string by initializing an instance of the String class:

var str = String("Hello, Swift!")

Swift String Example

import Foundation

// Creating strings using different methods
var stringA = "Hello, Swift!"
print(stringA)

var stringB: String = "Hello, Swift!"
print(stringB)

var stringC = String("Hello, Swift!")
print(stringC)

Output

Hello, Swift!
Hello, Swift!
Hello, Swift!

Swift Empty String:

An empty string in Swift is a string that contains no characters. It is represented by double quotes ("") and is commonly used to initialize string variables before assigning values dynamically.

How to Create an Empty String in Swift

You can create an empty string in Swift using:


1. String Literals ("")

2. The String Class (String(""))


Syntax

1. Using String Literal

var str = ""
var str: String = ""

2. Using String Class

var str = String("")

Example: Creating and Using an Empty String in Swift

The following Swift program demonstrates how to create and modify empty strings:

import Foundation

// Creating empty strings using different methods
var stringA = ""
var stringB: String = ""
var stringC = String("")

// Appending values to empty strings
stringA = "Hello"
stringB = "Swift"
stringC = "Blue"

print(stringA)
print(stringB)
print(stringC)

Output

Hello
Swift
Blue

Swift isEmpty Property

In Swift, we can check whether a string is empty using the isEmpty property. This Boolean property returns:

true โ†’ If the string contains no characters

false โ†’ If the string has one or more characters

Example: Check if a String is Empty in Swift

import Foundation

// Creating an empty string
var stringA = ""

if stringA.isEmpty {
print("stringA is empty")
} else {
print("stringA is not empty")
}

// Creating a non-empty string
let stringB = "Swift Programming"

if stringB.isEmpty {
print("stringB is empty")
} else {
print("stringB is not empty")
}

Output

stringA is empty
stringB is not empty

Why Use an Empty String?

  • Initializing string variables before assigning values
  • Placeholder for dynamic content in user input fields
  • Avoiding null values in string operations

Understanding Mutable & Immutable Strings

In Swift, strings can be categorized into two types based on whether their values can change after declaration:

1. Mutable Strings

๐Ÿ”น Mutable strings allow modifications after creation.
๐Ÿ”น They are declared using the var keyword.

Example: Creating a Mutable String in Swift

import Foundation

// stringA can be modified
var stringA = "Hello, Swift!"
stringA += " --Readers--"
print(stringA)

Output

Hello, Swift! --Readers--

2. Immutable Strings

๐Ÿ”น Immutable strings cannot be modified once created.
๐Ÿ”น They are declared using the let keyword.
๐Ÿ”น Any attempt to modify an immutable string will result in an error.


Example: Creating an Immutable String in Swift

import Foundation

// stringB cannot be modified
let stringB = "Hello, Swift!"
stringB += " --Readers--" // โŒ This will cause an error
print(stringB)

Output

ERROR!
/tmp/GeEN982WUU/main.swift:5:9: error: left side of mutating operator isn't mutable: 'stringB' is a 'let' constant
stringB += " --Readers--" // โŒ This will cause an error
/tmp/GeEN982WUU/main.swift:4:1: note: change 'let' to 'var' to make it mutable
let stringB = "Hello, Swift!"
^~~
var

String Interpolation in Swift

String interpolation is a powerful and convenient technique for dynamically creating strings by embedding the values of constants, variables, literals, and expressions inside a string literal. To insert these values, wrap them in parentheses () and prefix them with a backslash \.

Syntax

let city = "Delhi"
var str = "I love \(city) "


Example

Swift program demonstrating string interpolation:

import Foundation

var varA = 20
let constA = 100
var varC: Float = 20.0

// String interpolation
var stringA = " \(varA) times \(constA) is equal to \(varC * 100) "

print(stringA)

Output

20 times 100 is equal to 2000.0

String Concatenation in Swift

String concatenation allows us to combine multiple strings into a single string. We use the + operator to merge strings or characters.

Example

import Foundation

let strA = "Hello, "
let strB = "Learn "
let strC = "Swift!"

// Concatenating three strings
var concatStr = strA + strB + strC

print(concatStr)

Output

Hello, Learn Swift!

String Length

Swift strings do not have a length property like some other languages. Instead, we use the count property to determine the number of characters in a string.

Example

Swift program to count the length of a string:

import Foundation

let myStr = "Welcome to Swift Programming"

// Count the length of the string
let length = myStr.count

print("String length: \(length)")

Output

String length: 29

Swift makes string manipulation easy and efficient with built-in methods and operators, making it a powerful tool for handling textual data in applications.

String Comparison in Swift

String comparison in Swift is done using the == operator, which checks whether two string variables or constants hold the same value. This operator returns a Boolean result: true if the strings match and false if they donโ€™t.

import Foundation

var stringA = "Hello, Swift!"
var stringB = "Hello, World!"

// Checking if the strings are equal
if stringA == stringB
{
print(" \(stringA) and \(stringB) are equal")
} else {
print(" \(stringA) and \(stringB) are not equal")
}

Output

Hello, Swift! and Hello, World! are not equal

String Iteration in Swift

Swift provides various ways to iterate through each character of a string. The for-in loop allows you to access each character sequentially, while enumerated() can be used to retrieve both index and character values.


Example 1: Iterating Over a String

import Foundation

let sampleString = "SwiftProgramming"
for char in sampleString
{
print(char, terminator: " ")
}

Output

S w i f t P r o g r a m m i n g

Example 2: Iterating with Index Using enumerated()

import Foundation

let sampleString = "Swift"
for (index, char) in sampleString.enumerated()
{
print("\(index) = \(char) ")
}

Output

0 = S
1 = w
2 = i
3 = f
4 = t

Unicode Strings in Swift

Swift uses Unicode to represent characters from multiple languages and symbols. It supports:

  • Unicode Scalars: A unique 21-bit number for each character.
  • Extended Grapheme Clusters: A sequence of Unicode scalars forming a single character.
  • UTF-8 and UTF-16 Representations: Encodings used for storage and processing.

Example: Accessing UTF-8 and UTF-16 Values

import Foundation

let unicodeText = "Swift๐Ÿš€"

print("UTF-8 Representation:")
for code in unicodeText.utf8
{
print(code)
}

print("\nUTF-16 Representation:")
for code in unicodeText.utf16
{
print(code)
}

Output

UTF-8 Representation:
83
119
105
102
116
240
159
154
128

UTF-16 Representation:
83
119
105
102
116
55357
56320

Swift String Functions

Swift provides a variety of built-in functions for string manipulation. Below are some of the most commonly used ones:

Function Description
enumerated() Returns index and character in a string.
forEach() Iterates over each character in a string.
hasPrefix() Checks if a string starts with a specified substring.
hasSuffix() Checks if a string ends with a specified substring.
randomElement() Returns a random character from the string.
remove() Removes a character at a specified position.
removeAll() Deletes all characters in a string.
reversed() Reverses the order of characters.
uppercased() Converts the string to uppercase.
lowercased() Converts the string to lowercase.

Understanding Swift-Characters


Introduction to Swift Characters

In Swift, a Character is a single-character string literal, such as "A", "!", or "c". It is represented by the Character data type, which is designed to handle a single Unicode character. This guide will walk you through the syntax, examples, and best practices for working with characters in Swift.

Syntax for Declaring a Character

To declare a character in Swift, use the following syntax:

var char: Character = "A"

Example: Storing Characters in Swift

import Foundation

let char1: Character = "A"
let char2: Character = "B"

print("Value of char1: \(char1)")
print("Value of char2: \(char2)")

Output

Value of char1: A
Value of char2: B

Key Rules for Characters in Swift

1. Single Character Only:

A Character variable can only hold a single character. Attempting to store more than one character will result in a compilation error.

// This will cause an error
let char: Character = "AB" // Error: Cannot convert 'String' to 'Character'



2. No Empty Characters:

You cannot create an empty Character variable or constant.

// This will cause an error
let char: Character = "" // Error: Cannot convert 'String' to 'Character'