Strings In Swift Programming Language

Introduction

In this article, we will implement the concept of Strings in Swift Programming Language. The concept of Strings is the same in all the languages but there is some difference between them. In Swift, we see a new concept of emoji and symbols. We will discuss further, the concept and how to implement these  symbols.

What is String?

Text is a common type that people use like name, address etc. Now,  we want to handle this text. For this purpose, we make another data type called String which stores string values.

In this image below, we simply declare two variables as firstName and lastName. Then, we assign the values to them. After this, we print our values separately. Then, we concatenate our two variables and show the combined result of two variables. Then, we declare one emoji and assign its value. After this, we copy the emoji symbols and print them in round brackets of print statement. We see that the result is same.

code

Code

var firstName = “Khawar”
var lastName = “Islam”

print(firstName)
print(lastName)

var fullName = firstName + lastName
print(fullName)

var 😊 = “Khawar”
var 😡 = “Islam”

print(😊+😡)


Concatenation

Sometimes, you need to sum up i.e. you need to concatenate your strings into single string. For that, you need an addition operator to concatenate the two strings, as shown below:

code

Code

var first = "Khawar"
var last = "Islam"

var fulname = "\(firstName) \(lastName)"


Interpolation

You can also build your string using interpolation which is special syntax of Swift and very easy to read and write.

code

Code

var first = "Khawar"

var fulname = " My Name is \(firstName) Islam"


Equality Methods

Sometimes, you want to compare two strings in order to check whether these strings are equal or not. And, sometimes, you need to check the number of alphabets to check which string is greater. So, the Equality operator is used for this purpose.

code

In this image above,  first, we assigned two variables with different names; then, checked  whether both strings are equal or not. Since they are not equal, it returns false. Then, we checked the number of alphabets in the second condition. The fName string is greater than the lName, so, it returns false again. Similarly, the last condition is doing the same, but I gave it the greater sign this time. So, the result is true.

Code

var fName = "Khawar"
var lName = "Islam"
fName == lName
fName < lName
fName > lName


Main Points

  • Unicode is the standard way for mapping characters into a number.
  • A single mapping in Unicode is called code point.
  • Character data type stores a single character.
  • String data type stores multiple characters.
  • Addition operator is used to combine the strings.

Up Next
    Ebook Download
    View all
    Learn
    View all