Swift programming for Beginners – Swift Characters and Strings

(Swift for Beginners)

Swift Characters and Strings

In this tutorial, you will learn about characters and strings usage in Swift. You’ll also learn different operations that can be performed on strings and characters.

What is a character?

A character is a single symbol (letter, number, etc.). Character in swift are of Character type and is declared as:

let someCharacter:Character

How to declare and assign a character in Swift?

You can assign value in Character type same as String using double quotes " " but it should contain only a single character inside the quotes " ".

If you need to include more than one character you need to define it String instead of Character.

Example 1: Declaring and assigning a character

let someCharacter:Character = “Hlet specialCharacter:Character = “@”

When you run the program, the output will be:


Example 2: Assigning more than one character (Doesn’t work)

But if you try to assign two symbols inside the character as

 This will give an error
 Changing the type to String will fix it.
let failableCharacter:Character = "H@"

When you try to run the above code, you will get an error as:

Cannot convert value of type String to Character.

Creating character using unicode and escape sequence

You can also create special type of characters for.e.g emoji using unicodes. You can create a unicode using escape sequence u{n} (unicode code point ,n is in hexadecimal).

Example 3: Creating a unicode character

let heartShape:Character = "u{2665}"

When you run the program, the output will be:

In the above example, a heart shape character was created from code U+2665. Although u{2665} is included in double quotes, compiler doesn’t treat it as a String because we used escape sequence u{n}. An escape sequence doesn’t represent itself when included in literal.

What is a String?

A string is simply a collection of characters. Strings in Swift are of String type and declared as:

let someString:String

How to declare and assign a string in Swift?

You can assign value in String type using string literals. A string literal is a collection of characters surrounded with double quotes " ".

Example 4: Declaring and assigning a string

let someString:String = "Hello, world!"
let someMessage = "I love Swift."

When you run the program, the output will be:

Hello, world!
I love Swift.

Here, both "Hello, world!" and "I love Swift." are string literals used to create string variables someString and someMessage respectively.

Operations on a string

There are some built in functions and property in String to deal with most frequently used operations. For example: to join strings, change it to uppercase or capitalize it. Let’s explore some frequently used operations below:

String comparison

You can simply check if two strings are equal or not using comparison operator (==). The operator returns returns true if both strings are equal, otherwise it returns false.

Example 5: String comparison in Swift

let someString = "Hello, world!"
let someMessage = "I love Swift."
let someAnotherMessage = "Hello, world!"
print(someString == someMessage)
print(someString == someAnotherMessage)

When you run the program, the output will be:


String concatenation

Two different strings value can be added together with the addition operator (+) or using compound assignment operator (+=). You can also append a character/string in a string using append method.

Example 6: String concatenation in Swift

let helloStr = "Hello, "
let worldStr = "World"
var result = helloStr + worldStr

When you run the program, the output will be:

Hello, World
Hello, World!

In the above program we created a string result by appending helloStr and worldStr using + operator. So, print(result) outputs Hello, World in the screen.

You can also append any character or string using append method. result.append("!") appends a ! character at the end of the string. So, print(result) outputs Hello, World! on the screen.

String concatenation using advanced assignment operator

We can also use advanced assignment operator (+=) to append string.

Example 7: String concatenation using += operator

var helloStr = "Hello, "
let worldStr = "World!"

helloStr +=  worldStr

When you run the program, the output will be:

Hello, World!

Notice the use of var instead of let in helloStr. If you have defined helloStr a constant using let, you cannot change it later using the += operator and eventually get an error. So, you have to define helloStr a variable.

String Interpolation

It is a simple process of evaluating a string literal that consists of variables, constants etc. Imagine you have player’s name and score stored in two constants as:

let playerName = "Jack"
let playerScore = 99

Now you need to display a message to the player as “Congratulations Jack!. Your highest score is 99.” Here, you need to a way to use the values of the constants in a single string.

This can be achieved using string concatenation as:

let congratsMessage = "Congratulations " + playerName + "!. Your highest score is " + playerScore + "."

However, you can see this can get messy pretty soon. You have to take care of the spaces after the word Congratulationsis. Also, if you have to use more than two constants/variables, it will get unreadable.

There’s an easier way to display the message using string interpolation. Interpolation is the process to include value of a variable or constant inside string literal.

The variable or constant that should insert into the string literal is wrapped in a pair of parentheses ( ), prefixed by a backslash ().

Example 8: String interpolation in Swift

let playerName = "Jack"
let playerScore = 99
let congratsMessage = "Congratulations (playerName)!. Your highest score is (playerScore)."

When you run the program, the output will be:

Congratulations Jack!. Your highest score is 99.

Some helpful built-in String functions & variables:

1. isEmpty

This function determines if a string is empty or not. It returns true if the string is empty otherwise, it returns false.

Example 9: isEmpty

var emptyString = ""

When you run the program, the output will be:


2. capitalized

This property is used to capitalize every word in a string.

Example 10: capitalized

let someString = "hello, world!"

When you run the program, the output will be:

Hello, World!

3. uppercased and lowercased

The uppercased function converts string to uppercase letter and the lowercased function converts string to lowercase letter.

Example 11: uppercased() and lowercased()

let someString = "Hello, World!"

When you run the program, the output will be:

hello, world!

4. Length/count

This property is used to count the total number of characters in a string.

Example 12: count

let someString = "Hello, World!"

When you run the program, the output will be:


5. hasPrefix

This function determines if a string starts with certain characters or not and returns a boolean value. It returns true if the string prefix matches with the provided value otherwise returns false.

Example 13: hasPrefix()

let someString = "Hello, World!"

When you run the program, the output will be:


6. hasSuffix

This function determines if a string ends with certain characters or not and returns a boolean value. It returns true if the string suffix matches with the provided value otherwise returns false.

Example 14: hasSuffix()


When you run the program, the output will be:




Personal Career & Learning Guide for Data Analyst, Data Engineer and Data Scientist

Applied Machine Learning & Data Science Projects and Coding Recipes for Beginners

A list of FREE programming examples together with eTutorials & eBooks @ SETScholars

95% Discount on “Projects & Recipes, tutorials, ebooks”

Projects and Coding Recipes, eTutorials and eBooks: The best All-in-One resources for Data Analyst, Data Scientist, Machine Learning Engineer and Software Developer

Topics included: Classification, Clustering, Regression, Forecasting, Algorithms, Data Structures, Data Analytics & Data Science, Deep Learning, Machine Learning, Programming Languages and Software Tools & Packages.
(Discount is valid for limited time only)

Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.

Learn by Coding: v-Tutorials on Applied Machine Learning and Data Science for Beginners

Please do not waste your valuable time by watching videos, rather use end-to-end (Python and R) recipes from Professional Data Scientists to practice coding, and land the most demandable jobs in the fields of Predictive analytics & AI (Machine Learning and Data Science).

The objective is to guide the developers & analysts to “Learn how to Code” for Applied AI using end-to-end coding solutions, and unlock the world of opportunities!