Swift String With Examples

Today we will look into Swift String operations. Furthermore, we’ll be discussing the changes in Strings with the introduction of Swift 4. Earlier we looked into Swift Function. Let’s open up our playground and dive right in.

Swift String

String in Swift is an ordered collection of values which are of the type Character.

Similar to Arrays, String defined with var are mutable and strings defined with let keyword are immutable.

Changes with Swift 4:
Now Strings conform to the collections protocol.
Hence Strings are Collections..
Methods such as reversed(), indexOf() etc that are applicable to collections are now applicable with Swift Strings directly too without the use of characters

Swift String initialization

There are numerous ways to initialize a String in Swift.


//initializing an empty string
var empty = ""            // Empty String
var anotherEmpty = String()       // Another way to initialize an empty string
var str = "Hello, playground" //String literal
var intToString = String(10) // returns "10", this can be used to convert any type to string
var boolToString = String(false) // returns "false"
//initialise a string using repeating values.
let char = "a"
let string = String(repeating: char, count: 5) //prints "aaaaa"
let newChar = "ab"
let newString = String(repeating: newChar, count: 5) //prints : "ababababab"

A string literal is a sequence of characters surrounded by double quotes (“).

Swift String Empty String check

To check if a string is empty or not we invoke the function isEmpty as shown below.


var empty = ""
var boolToString = String(false) // returns "false"
if empty.isEmpty
{
 print("string is empty")
}
if !boolToString.isEmpty
{
 print("string is not empty")
}

Appending Strings

Strings and characters can be appended to a string using the append() function or the += operator as shown below.


var myString =  "Hello"
myString += " World" //returns "Hello World"
myString.append("!") //returns "Hello World!"
print(myString) //prints "Hello World!n"

String Interpolation

String interpolation is a way to construct a new String value from a mix of constants and variables.
Each item that you insert into the string literal is wrapped in a pair of parentheses, prefixed by a backslash () as shown below:


let multiplier = 2
let message = "(multiplier) times 2.5 is (Double(multiplier) * 2.5)" //prints "2 times 2.5 is 5.0"

Iterating through a String

Iterating over a String to fetch each character in Swift 3 is done using a for-in loop in the following manner(s):


//using characters property
for character in myString.characters
{
 print(character)
}
//using indices property.
for character in myString.characters.indices
{
 print(myString[character])
}
//using enumerated() func
for (index,character) in myString.characters.enumerated()
{
 print(character)
}
//prints:
H
e
l
l
o
W
o
r
l
d
!

enumerated() : Returns a sequence of pairs (n, x), where n represents a consecutive integer starting at zero, and x represents an element of the sequence.

Changes in Swift 4:
characters is now deprecated in Swift 4.

Retrieving characters in swift 4.


for character in myString {
    print(character)
}

Swift String Length

Length of a string is retrieved as follows.


let myString = "Too many characters here!"
print(myString.characters.count) //prints 25

Successive properties namely characters and count are used to get the length of a string.

In Swift 4:
To get the length of a Swift String we just need to call myString.count.

Multi-Line String Literals

With Swift 4 following is the way to define a multiline string literals using triple quotes:


let multiLineString = """
Line 1
Line 2 goes here
Line 3 goes here
"""

Swift 4 compiler adds a new line by default at the end of each line.
To prevent this default behavior we need to use a backslash ().


let multiLineString = """
Line 1
Line 2 goes here,
Line 3 goes here
"""
print(multiLineString)
//Prints
//Line 1
//Line 2 goes here, Line 3 goes here

String Comparison

Swift String doesn’t have equals method like other languages. It checks the values using == and !=


var stringA = "string"
var stringB = "string"
var stringC = "new string"
stringA == stringB //prints true
stringB != stringC //prints true

Important Functions for Strings in Swift

Swift provides quite a number of powerful functions that can be used for performing operations on Strings.
The best thing about these functions is the high level of readability they’ve got to offer.

Convert to upper and lower case


var myString = "Hello World!"
myString.lowercased() returns "hello world!"
myString.uppercased() //returns "HELLO WORLD!"

Prefix and Suffix


myString.hasPrefix("Hello") //returns true
myString.hasPrefix("hello") //returns false
myString.hasSuffix("!") //returns true
//Alternative approach
String(myString.characters.prefix(2)) //returns "He"
String(myString.characters.suffix(3)) //returns "ld!"

prefix(maxLength) and suffix(maxLength) returns a substring with the first and last n number of characters respectively based on the number entered.

String start and end index


var myString = "Hello World!"
myString.startIndex //returns 0
myString.endIndex //returns 12

Insert and remove character from String


myString.insert("!", at: myString.endIndex) // "Hello World!!"
myString.insert("!", at: myString.startIndex) // "!Hello World!!"
myString.remove(at: myString.startIndex) //returns "!"
print(myString) // "Hello World!!n"

Note: at: expects an argument of type String.Index. Int won’t work(Atleast not in Swift 3)


myString.insert(contentsOf: "Hey".characters, at: myString.endIndex) // returns "Hello World!Hey"

Retrieve other indexes


var myString = "Hello World!"
let startIndexPlusTwo = myString.index(myString.startIndex, offsetBy: 2)
let endIndexMinusFour = myString.index(myString.endIndex, offsetBy: -4)
myString[startIndexPlusTwo] //returns "l"
myString[endIndexMinusFour] //returns "r"
myString[myString.index(before: startIndexPlusTwo)] // returns "e"
myString[myString.index(after: startIndexPlusTwo)] //returns "l"

startIndexPlusTwo and endIndexMinusFour is of the type String.Index. Only type String.Index is accepted inside myString[]. Not Int.

Index of a character


var myString = "Hello World!"
myString.characters.index(of: "o") // returns 4
myString.characters.index(of: "f") // returns nil

index(of:) returns the index of the first matching character

Swift String substring

We can retrieve a substring between indexes as follows.


var myString = "Hello World!"
let startIndexPlusTwo = myString.index(myString.startIndex, offsetBy: 2)
let endIndexMinusFour = myString.index(myString.endIndex, offsetBy: -4)
myString[startIndexPlusTwo..<myString.endIndex] //returns "llo World!"
myString[myString.startIndex..<startIndexPlusTwo] //returns "He"
//Alternate approach
myString.substring(to: startIndexPlusTwo) //returns "He"
myString.substring(from: startIndexPlusTwo) //returns "llo World!"
myString.substring(with: startIndexPlusTwo..<endIndexMinusFour) // "llo Wo"
var mySubString = String(myString.characters.suffix(from: startIndexPlusTwo)) //returns "llo World!"

substring(to:) returns the substring from the startIndex to the index set.
substring(from:) returns the substring from the index set to the end index.
substring(with:) returns the substring between the range of indexes entered.

Search For A Substring

Searching for a substring is done using the function range(of:). This function returns an optional type which is a range of indexes of the type Range?, hence we’ll need to unwrap it to use the range.


if let myRange = myString.range(of: "Hello"){
myString[myRange] //returns "Hello"
}
else{
 print("No such substring exists")
}
//In case when the substring doesn't exist
if let myRange = myString.range(of: "Hlo"){
myString[myRange]
}
else{
 print("No such substring exists") //this is printed
}

Replacing/Removing a Substring from Swift String

The functions replaceSubrange and removeSubrange are used for replacing and removing a substring from a string as shown below.


var myString = "Hello World!"
//replacing
if let myRange = myString.range(of: "Hello"){
myString.replaceSubrange(myRange, with: "Bye") //returns "Bye World!"
}
else{
 print("No such substring exists")
}
//removing
if let myRange = myString.range(of: "Hello "){
myString.removeSubrange(myRange) //returns "World!"
}
else{
 print("No such substring exists")
}

Swift String split

To split a string we use the function components(separatedBy:). The function expects a parameter of the type Character or String as shown below:


var myString = "Hello How You Doing ?"
var stringArray = myString.components(separatedBy: " ") //returns ["Hello", "How", "You", "Doing", "?"]
for string in stringArray
{
    print(string)
}
//prints:
Hello
How
You
Doing
?

Changes in Swift 4: Swift 4 has made Substring as a type too along with String.

Substring as a type

Substring which is a subsequence of strings is also a type now. Hence when we split the string in Swift 4, we get an array of Substring type. Each of the elements is of the type Substring as shown below.


var myString = "Hello How You Doing ?"
var substrings = myString.split(separator: " ")
type(of: substrings) //Array<Substring>.Type
type(of: substrings.first!) //Substring.Type
var newStringFromSub = String(substrings.first!) // "Hello"

Note: type is a function which returns the type of the argument passed.

This brings an end to Swift String tutorial. We’ve covered all the bases and implementation of Strings in Swift and also discussed the new changes in Swift 4.

By admin

Leave a Reply

%d bloggers like this: