Open In App

Strings in Swift

Last Updated : 29 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Swift 4 strings have requested an assortment of characters, for example, “Welcome GeeksforGeeks” and they are addressed by the Swift 4 information type String, which thus addresses an assortment of upsides of Character type.

Strings in Swift are Unicode right and region obtuse and are intended to be productive. Strings are utilized for text/characters. For example, “Welcome GeeksforGeeks” is a series of characters. Strings in Swift are encoded with UTF-8. An encoding like UTF-8 decides how an information point like Unicode’s \u{61} is put away in bytes. You can contrast that with the jargon and words you use (Unicode), and left-to-right or right-to-left (encoding).

Or we can say that a string is an information type and is much of the time carried out as an exhibit information construction of bytes (or words) that stores a succession of components, regular characters, utilizing some person encoding. The string may likewise signify more broad clusters or other successions (or rundown) data types and designs.

Creating a String

Strings are the most important part of Swift to represent data in the textual form. To create a string variable you can use the String keyword or simply create a variable with string literals. A string literal is a sequence of characters surrounded by double quotes. 

Syntax:

// single line string

var str: String = “Hello GeeksforGeeks”

var str2 = “Long live”

Example:

Swift




// Swift program to illustrate how to create a string
 
// String creation using String literal
var stringA = "Hello, Geeksforgeeks!"
print(stringA)
 
// String creation using String instance
var stringB = String("Hello, Geeksforgeeks!")
print(stringB)
 
// String creation using String keyword
var stringC : String = "Hey GFG"
print(stringC)


Output:

Hello, Geeksforgeeks!
Hello, Geeksforgeeks!
Hey GFG

Multi-Line String

As the name suggested multi-line string contains multiple lines in it. To create a multi-line string we need to use three double quotes marks around the sequence of characters. Or we can say that the multi-line string literal is surrounded by the three double quotation marks and the string starts from the first line after the opening quotation marks and ends on the line before the closing quotation marks.

Syntax:

“””

Hello GeeksforGeeks

How are you?

What are you doing?

“””

Example:

Swift




// Swift program to illustrate how to multi-line string
 
// Creating multi-line string
let str = """
Hey this is a
example of multiple Line
string by GFG
"""
 
print(str)


Output:

Hey this is a
example of multiple Line
string by GFG 

Empty String

An empty string is a string that is assigned with memory but the length of the string is 0.  In Swift, we can create an empty string either by assigning an empty string literal to a variable or initializing a new String instance with an initializer.

Syntax:

var str = “”

var str = String()

To check if the given string is empty of not Swift provides an inbuilt isEmpty property. This property will return true if the given string is empty. Otherwise, it will return false.

Syntax:

str.isEmpty

Example:

Swift




// Swift program to check if the given string is empty or not
 
// Creating empty string using String literal
var stringA = ""
 
// Checking if the given string is empty or not
if stringA.isEmpty {
   print("stringA is empty")
} else {
   print("stringA is not empty")
}
 
// Creating empty string using String instance
let stringB = String()
 
if stringB.isEmpty {
   print("stringB is empty")
} else {
   print("stringB is not empty")
}


Output:

stringA is empty
stringB is empty

String Concatenation

String concatenation is a process of adding two or more strings together to create a new string. Swift supports the following methods to concatenate strings:

1. Using addition operator(+): To concatenate two or more strings we can use the addition operator(+). It creates a new string by concatenating the given strings.

Syntax:

var res = str1 + str2

2. Using addition assignment operator(+=): We can also use the addition assignment operator to concatenate two strings.

Syntax:

var res += str1

3. Using append() function: To concatenate strings we can also use the append() method. It adds a new element at the end of the specified mutable string. It does not create a new string instead it modifies the original string. 

Syntax:

str1.append(str2)

Example:

Swift




// Swift program to illustrate string concatenation
 
// Creating strings
let str1 = "Hello"
let str2 = "Geeksforgeeks"
 
// Concatenating two strings
var result = str1 + str2
 
print("Resultant string:", result)


Output:

Resultant string: HelloGeeksforgeeks

String Comparison

String comparison is a method to check if the given two strings are equal to each other or not. If they are equal, then it returns true. If they are not equal, then it will return false. Swift support two comparison operators and they are: equal to operator(==) and not equal to operator(!=). 

Syntax:

string1 == string 2

Example:

Swift




// Swift program to illustrate string comparison
 
// Creating strings
var varA = "Hello, Swift 4!"
var varB = "Hello, World!"
 
// Checking if the given strings are 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 Length

The number of characters that make up a string is known as the length of a string. We can track down the length of the string using the count property. It returns the total length of the string. Swift strings can be treated as a variety of individual characters so this property counts each character to find the total length. 

Syntax:

str.count

Example:

Swift




// Swift program to illustrate string interpolation
 
// Creating a string
var varA = "Hello, Geeksforgeeks"
 
// Finding the length of the string
print("\(varA), length is \((varA.count))")


Output:

Hello, Geeksforgeeks, length is 20

String Interpolation

String interpolation is used to create a new string by mixing the values of constants, variables, literals, and expressions. In String interpolation, the values of the variables and constants which you want to insert into a string literal are wrapped in a pair of parentheses, prefixed by a backslash(\). You are also allowed to interpolate single-line or multi-line string literals. 

Syntax:

var str = “hello \(geeksforgeeks)”

Example:

Swift




// Swift program to illustrate string interpolation
 
// Creating variables
var varA = 50
let constA = 100
var varC:Float = 50.0
 
// String interpolation
var stringA = "\(varA) times \(constA) is equal to \(varC * 100)"
print(stringA)


Output:

50 times 100 is equal to 5000.0

String Iterating

As we know that a string is a collection of values in Swift 4, so to iterate over a string we use for-in loop. This loop goes through each character of the given string. 

Example

Swift




// Swift program to illustrate how to iterate through string
 
// Here we are using for-in loop to iterate through
// each character of the string
for chars in "WelcomeToGeeksforgeeks"
{
   print(chars, terminator: " ")
}


Output:

W e l c o m e T o G e e k s f o r g e e k s

String Properties and Functions

The following table shows the commonly used properties, functions, and operators to perform different tasks:

Name    

Usage

isEmpty It is used to check whether a string is empty or not. It specifies a Boolean value.
hasPrefix(prefix: String) It is a function to check whether a given parameter string exists as a prefix of the string or not.
hasSuffix(suffix: String) It is a function to check whether a given parameter string exists as a suffix of the string or not.
toInt() It is a function to convert a numeric String value into Integer.
count It is a property to count the number of Characters in a string.
utf8 It specifies a property to return a UTF-8 representation of a string.
utf16 It specifies a property to return a UTF-16 representation of a string.
unicodeScalars It specifies a property to return a Unicode Scalar representation of a string.
+ It is an operator to concatenate two strings, or a string and a character, or two characters.
+= It is an operator to append a string or character to an existing string.
== It is an operator to determine the equality of two strings.
< It is an operator to perform a lexicographical comparison to determine whether one string evaluates as less than another.
startIndex It is used to get the value at starting index of the string.
endIndex  It is used to get the value at the ending index of the string.
Indices It is used to access the indices one by one. i.e. all the characters of the string one by one.
insert(“Value”, at: position)                It is used to insert a value at a position.
remove(at: position)
removeSubrange(range)             
It is used to remove a value at a position or can remove a range of values from a string.
lowercase() This function is used to convert the string into lowercase.
uppercase() This function is used to convert the string into uppercase.
reversed() It is used to return the reverse of a string.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads