Swift – Strings


Swift – Strings



”;


Strings in Swift are an ordered collection of characters, such as “Hello, World!” and they are represented by the Swift 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

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)

Output


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

Empty String in Swift

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)

Output


Hello
Swift
Blue

Using the isEmpty property

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" )
}

Output


stringA is empty
stringB is not empty

String Mutability in Swift

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)

Output


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)

Output


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 in Swift

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)

Output


20 times 100 is equal to 2000.0

String Concatenation in Swift

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)

Output


Hello,LearnSwift!

String Length in Swift

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)")

Output


String length: 25

String Comparison in Swift

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" )
}

Output


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

String Iterating in Swift

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: " ")
}

Output


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)")
}

Output


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

Unicode Strings in Swift

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) ")
}

Output


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

String Functions & Operators in Swift

Swift supports a wide range of methods and operators related to Strings −






















S.No Functions/Operators & Purpose
1

isEmpty

A Boolean value that determines whether a string is empty or not.

2

hasPrefix(prefix: String)

Function to check whether a given parameter string exists as a prefix of the string or not.

3

hasSuffix(suffix: String)

Function to check whether a given parameter string exists as a prefix of the string or not.

4

toInt()

Function to convert numeric String value into Integer.

5

count()

Global function to count the number of Characters in a string.

6

utf8

Property to return a UTF-8 representation of a string.

7

utf16

Property to return a UTF-16 representation of a string.

8

unicodeScalars

Property to return a Unicode Scalar representation of a string.

9

+

Operator to concatenate two strings, or a string and a character, or two characters.

10

+=

Operator to append a string or character to an existing string.

11

==

Operator to determine the equality of two strings.

12

<

Operator to perform a lexicographical comparison to determine whether one string evaluates as less than another.

13

==

Operator to determine the equality of two strings.

14

startIndex

To get the value at starting index of string.

15

endIndex

To get the value at ending index of string.

16

Indices

To access the indices one by one. i.e. all the characters of string one by one.

17

insert(“Value”, at: position)

To insert a value at a position.

18

remove(at: position)

removeSubrange(range)

to remove a value at a position, or to remove a range of values from string.

19

reversed()

returns the reverse of a string.

Advertisements

”;

Leave a Reply

Your email address will not be published. Required fields are marked *