Swift String

Swift String

String in Swift is an ordered collection of values that are of the type of Character. Similar to Arrays, String defined with var are mutable and strings defined with let keyword are immutable.

import Foundation

var title = "baluTutorial"
let subTitle = "Programming is fun" //immutable

From Swift 4 onwards Strings conform to the collections Protocols(Swift protocols), 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.

import Foundation

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"

// initialize 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"

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.

import Foundation

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.

import Foundation

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:

import Foundation

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 forin loop in the following manner(s):

import Foundation

let myString = "balututorial.com"

for character in myString {
 print(character)
}

//using indices property.
for character in myString.indices {
 print(myString[character])
}

//using enumerated() func
for (index,character) in myString.enumerated() {
    print("\(index):\(character)")
}

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.

Swift String Length

The length of a string is retrieved as follows.

import Foundation

let myString = "balututorial.com"
print(myString.count) //prints 16

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 multiline string literals using triple quotes:

import Foundation

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

print(multiLineString)

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 (\).

import Foundation

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

print(multiLineString)

String Comparison

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

import Foundation

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

import Foundation

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

Prefix and Suffix

import Foundation

var myString = "Hello World!"
myString.hasPrefix("Hello") //returns true
myString.hasPrefix("hello") //returns false
myString.hasSuffix("!") //returns true

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

import Foundation

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

Insert and remove a character from String

import Foundation

var myString = "Hello World!"

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

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

Insert multiple characters/substring

import Foundation

var myString = "Hello World!"
myString.insert(contentsOf: "Hey", at: myString.endIndex)
print(myString) //Hello World!Hey

Retrieve other indexes

import Foundation

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 are of the type String.Index. Only type String.Index is accepted inside myString[]. Not Int.

Index of a character

import Foundation

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

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

Swift String substring

We can retrieve a substring between indexes as follows.

import Foundation

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"

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.

import Foundation

var myString = "Hello World!"
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.

import Foundation

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")
}
Note: For replace we can use myString.replacingOccurrences(of: “Hello”, with: “Bye”)

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:

import Foundation

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

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.

import Foundation

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"

whatsapp

error: Content is protected !!