Swift Strings



Strings in Swift are an ordered collection of characters, such as "Hello, World!" and they are represented by the data type String, which in turn represents a collection of values of characters. Or we can say that Strings are used to represent textual information.

Create a String

In Swift, we can create a string in two different ways, either by using a string literal or by creating an instance of a String class.

Syntax

Following is the syntax for string −

// Using String literal
var str = "Hello"
var str : String = "Hello" 

// Using String class
var str = String("Hello")

Example

Swift program to demonstrate how to create a string.

import Foundation

// Creating string using String literal
var stringA = "Hello, Swift!"
print(stringA)

// Creating string by specifying String data type
var stringB : String = "Hello, Swift!"
print(stringB)

// Creating string using String instance
var stringC = String("Hello, Swift!")
print(stringC)

The output of the above code is:

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

Creating an Empty String

An empty string is a string that contains nothing. It is represented by double quotes with no characters. It is generally used to initialize string variables before they receive value dynamically. We can create an empty String either by using an empty string literal or creating an instance of a String class.

Syntax

Following is the syntax for empty string −

// Using String literal
var str = ""
var str : String = "" 

// Using String class
var str = String("")

Example

Swift program to demonstrate how to create an empty string.

import Foundation

// Creating empty string using String literal
var stringA = ""

// Creating empty string by specifying String data type
var stringB : String = ""

// Creating string using String instance
var stringC = String("")

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

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

The output of the above code is:

Hello
Swift
Blue

Iterating Over String Characters

String iterations are used to traverse through each character of the specified string and can perform operations on the accessed information. We can iterate through a given string using a for-in loop.

Example

import Foundation
var str = "ThisString"
for s in str {
   print(s, terminator: " ")
}

The output of the above code is:

T h i s S t r i n g

We can also use the enumerated() function with a for-in loop to get both character and their respective index.

Example

import Foundation

var str = "ThisString"
for (index, value) in str.enumerated() {
   print("\(index) = \(value)")
}

The output of the above code is:

0 = T
1 = h
2 = i
3 = s
4 = S
5 = t
6 = r
7 = i
8 = n
9 = g

Checking Empty String

We can also check whether a string is empty or not using the Boolean property isEmpty. If the specified string is empty, then it will return true. Or if the specified string contains some letters, then it will return false.

Example

Swift program to check whether the given string is an empty string or not.

import Foundation

// Creating empty string using String literal
var stringA = ""

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

// Creating string
let stringB = "Tutorialspoint"

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

The output of the above code is:

stringA is empty
stringB is not empty

String Mutability

We can categorize a string into two types according to its ability to change after deceleration.

  • Mutable strings: Mutable strings are those strings whose values can change dynamically after creation. Mutable strings are created using the var keyword.

  • Immutable Strings: Immutable strings are those strings whose values cannot change after creation, if we try to change its value we will get an error. If we want to modify the immutable string, then we have to create a new string with the modified changes. Immutable strings are created using the let keyword.

Example of Mutable Strings

Swift program to create a mutable string.

import Foundation

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

The output of the above code is:

Hello, Swift 4!--Readers--

Example of immutable Strings

Swift program to create an immutable string.

import Foundation

// stringB can not be modified
let stringB = String("Hello, Swift 4!")
stringB += "--Readers--"
print(stringB)

The output of the above code is:

main.swift:5:9: error: left side of mutating operator isn't mutable: 'stringB' is a 'let' constant
stringB += "--Readers--"
~~~~~~~ ^
main.swift:4:1: note: change 'let' to 'var' to make it mutable
let stringB = String("Hello, Swift 4!")
^~~
var

String Interpolation

String interpolation is a powerful and convenient technique to create a new string dynamically by including the values of constants, variables, literals, and expressions inside a string literal. Each item (variable or constant or expression) that we want to insert into the string literal must be wrapped in a pair of parentheses, prefixed by a backslash (\).

Syntax

Following is the syntax for string interpolation −

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

Example

Swift program for 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)

The output of the above code is:

20 times 100 is equal to 2000.0

String Concatenation

String concatenation is a way of combining two or more strings into a single string. We can use the + operator to concatenate two strings or a string and a character, or two characters.

Syntax

Following is the syntax for string concatenation −

var str = str1 + str2

Example

Swift program for string concatenation.

import Foundation

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

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

print(concatStr)

The output of the above code is:

Hello,LearnSwift!

String Length

Swift strings do not have a length property, but we can use the count property to count the number of characters in a string.

Example

Swift program to count the length of the string.

import Foundation

let myStr = "Welcome to TutorialsPoint"

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

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

The output of the above code is:

String length: 25

String Comparison

We can use the "==" operator to compare two strings of variables or constants. This operator returns a boolean value. If the given strings are equal, then it will return true. Otherwise, it will return false.

Example

Swift program to check whether the given strings are equal or not.

import Foundation

var varA   = "Hello, Swift 4!"
var varB   = "Hello, World!"

// Checking whether the given string is equal or not
if varA == varB {
   print( "\(varA) and \(varB) are equal" )
} else {
   print( "\(varA) and \(varB) are not equal" )
}

The output of the above code is:

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

Swift Unicode Strings

Unicode is a standard way of representing text in different writing systems. Or we can say, that it is used to represent a wide range of characters and symbols. The following are some important points of Unicode −

  • Character Representation − All the characters present in the string have Unicode scalar values. It is a 21-bit unique number that represents a character. All types of characters and symbols from various languages have Unicode scalar values.

  • Extended Grapheme Clusters − Extended grapheme clusters are used to represent human-readable characters. It can be a collection of one or more Unicode scalars that represent a single character.

  • Unicode Scalars − With the help of Unicode Scalars property we can easily access the Unicode scalar value of the given character.

  • String comparison with Unicode − While comparing two strings, Swift automatically performs a Unicode-complaint comparison. It makes sure that the strings are compared according to their linguistic meaning, not their binary value.

Example

Swift program to access a UTF-8 and UTF-16 representation of a String by iterating over its utf8 and utf16 properties as demonstrated in the following example −

import Foundation

var unicodeString   = "Dog"
print("UTF-8 Codes: ")
for code in unicodeString.utf8 {
   print("\(code) ")
}
print("\n")

print("UTF-16 Codes: ")
for code in unicodeString.utf16 {
   print("\(code) ")
}

The output of the above code is:

UTF-8 Codes: 
68 
111 
103 
226 
128 
188 
240 
159 
144 
182
UTF-16 Codes: 
68 
111 
103 
8252 
55357 
56374 

Swift String Functions

Below is list of all functions from Swift String.

Sr.No. Functions & Description
1 enumerated()

It is used to iterate over the given string and return each character and its respective index value.

2 forEach()

It is used to iterate through each character of the given string just like the for-in loop.

3 hasPrefix()

It is used to determine whether the given string begins with the specified string or not.

4 hasSuffix()

It is used to determine whether the given string ends with the specified string.

5 randomElement()

It is used to find a random character from the given string.

6 remove()

It is used to remove specified characters from the given position.

7 removeAll()

It is used to remove the whole characters from the given string.

8 removeFirst()

It is used to remove the characters from the beginning of the given string.

9 removeLast()

It is used to remove the last characters from the given string.

10 removeSubrange()

It is used to remove a range of characters from the specified string.

11 reversed()

It is used to reverse the order of the given string.

12 shuffled()

It is used to shuffle all the characters present in the given string.

13 dropFirst()

It is used to remove the specified number of characters from the start of the given string.

14 dropLast()

It is used to remove the specified number of characters from the end of the given string.

15 lowercased()

It is used to convert the given string into lowercase.

Swift String Properties

Below is the list of commonly used properties available in Swift's String type:

Sr.No. Properties & Description
1 isEmpty

It checks whether the given string is empty or not.

2 first

It returns the first character of the string.

3 last

It returns the last character of the string.

Advertisements