Swift programming for Beginners – Swift Data Types

(Swift for Beginners)

Swift Data Types

In this tutorial, you will learn about different data types that Swift programming language supports and use it while creating a variable or a constant.

A data type is the type of data (value) a variable or constant can store in it. For example, in the article Swift Variables and Constants, you created a variable and a constant to store string data in the memory.

This data can be a text/string (“Hello”) or a number (12.45) or just bits (0 &1). Defining the data type ensures only the defined type of data is stored.

Let’s look at a scenario:

Suppose you want to create a game. Since, most games display high score and player’s name after the game completes, you need to store these two data for your game.

The high score is a number (e.g. 59) and player’s name a string(e.g Jack). You can create two variables or constants to store the data.

In Swift, this can be done by declaring variables and the data type as:

var highScore:Int = 59
var playerName:String = "Jack"

Here, we declared highScore variable of type Int which stores value 59. And, playerName variable of type String which stores value Jack.

However, if you do something like this:

var highScore:Int = "Jack"

You will get a compile time error stating cannot convert value of type ‘String’ to specified type ‘Int’.

It’s because you declared highScore to store integer value but placed string in it. This error ensures highScore can only store a number and not player’s name.


Size of a Data Type

Another important part of a data type is its size. This specifies the size of data that can be stored in a given variable or constant.

Type’s size is measured in terms of bit and can store values upto 2bits. If you don’t know about Bit, think of it as a value that is either 0 or 1.

So, for a Type size = 1 bit, it can only store upto, 21 = 2, two values: either 0 or 1. So a 1 bit system for a letter program can interpret 0 as a/0 and 1 as b/1.0.

0 -> a or 0 
1 -> b or 1

Likewise, a two bit system can store upto 22 = 4 values: (00,01,10,11) and each combination can be represented as:

00 -> a or 0
01 -> b or 1
11 -> c or 2
10 -> d or 3

For a n bit system, it can store a maximum of 2n values in it.


Swift Data Types

The most common data types used in swift are listed below:

Bool

  • Variable/Constant declared of Bool type can store only two values either true or false.
  • Default Value: false
  • It is frequently used when you work with if-else statement. Swift if else article covers in detail about it.

 

Example 1: Boolean data type

let result:Bool = true
print(result)

When you run the program, the output will be:

true

Integer

  • Variable/Constant declared of integer type can store whole numbers both positive and negative including zero with no fractional components .
  • Default Value: 0
  • Size: 32/64 bit depends on the platform type.
  • Range: -2,147,483,648 to 2,147,483,647 (32 bit platform)
    -9223372036854775808 to 9223372036854775807 (64 bit platform
  • There are many variants of Integer type.e.g. UIntInt8Int16 etc. The most common one you use is of Int.
  • If you have a requirement to specify the size/type of integer a variable/constant can hold, you can store it more specifically using UIntInt8Int16 etc. which we are going to explore below.

 

Example 2: Integer data type

var highScore:Int = 100
print(highScore)

highScore = -100
print(highScore)

When you run the program, the output will be:

100
-100

In the above example we declared a variable highScore of type Int. First, we assigned it with a value of 100 so print(highScore) outputs 100 in the screen.

Later, we changed the value to -100 using assignment operator as highScore = -100 so, print(highScore) outputs -100 in the screen.


Int8

  • Variant of Integer type that can store both positive and negative small numbers.
  • Default Value: 0
  • Size: 8 bit
  • Range: -128 to 127

 

Int8 integer can store altogether 28 = (256) values in it. i.e it can store numbers from 0 to 255 right?

Yes, you are correct. But since, Int8 includes both positive and negative numbers we can store numbers from -128 to 127 including 0 which totals to 256 values or numbers.

var highScore:Int8 = -128//ok
highScore = 127 //ok
highScore = 128 // error here
highScore = -129 //error here

You can also find out the highest and lowest value a type can store using .min and .max built in Swift functions.

Example 3: Max and Min Int8 data type

print(Int8.min)
print(Int8.max)

When you run the program, the output will be:

-128
127

UInt

  • Variant of Integer type called UInt (Unsigned Integer) which can only store unsigned numbers (positive or zero).
  • Default Value: 0
  • Size: 32/64 bit depends on the platform type.
  • Range: 0 to 4294967295 (32 bit platform)
    0 to 18446744073709551615 (64 bit platform)

 

Example 4: UInt data type

var highScore:UInt = 100
highScore = -100//compile time error when trying to 

The above code will give you a compile time error because a Unsigned Integer can only store either 0 or a positive value. Trying to store a negative value in an Unsigned Integer will give you an error.


Float

  • Variables or Constants declared of float type can store number with decimal or fraction points.
  • Default Value: 0.0
  • Size: 32 bit floating point number.
  • Range: 1.2*10-38 to 3.4 * 1038 (~6 digits)

 

Example 5: Float data type

let highScore:Float = 100.232
print(highScore)

When you run the program, the output will be:

100.232

Double

  • Variables / Constants declared of Double type also stores number with decimal or fraction points as Float but larger decimal points than Float supports.
  • Default value : 0.0
  • Size: 64-bit floating point number. (Therefore, a variable of type Double can store number with decimal or fraction points larger than Float supports)
  • Range: 2.3*10-308 to 1.7*10308 (~15 digits)

 

Example 6: Double data type

let highScore:Double = 100.232321212121
print(highScore)

When you run the program, the output will be:

100.232321212121

Character

  • Variables/Constants declared of Character type can store a single-character string literal.
  • You can include emoji or languages other than english as an character in Swift using escape sequence u{n} (unicode code point ,n is in hexadecimal).

 

Example 7: Character data type

let playerName:Character = "J"
let playerNameWithUnicode:Character = "u{134}"
print(playerName)
print(playerNameWithUnicode)

When you run the program, the output will be:

J
Ĵ

String

  • Variables or Constants declared of String type can store collection of characters.
  • Default Value“” (Empty String)
  • It is Value type. See Swift value and Reference Type.
  • You can use for-in loop to iterate over a string. See Swift for-in loop.
  • Swift also supports a few special escape sequences to use them in string. For example,
    •  (null character),
    • \ (a plain backslash ),
    • t (a tab character),
    • v (a vertical tab),
    • r (carriage return),
    • " (double quote),
    • ' (single quote), and
    • u{n} (unicode code point ,n is in hexadecimal).

 

Example 8: String data type

let playerName = "Jack"
let playerNameWithQuotes = ""Jack""
let playerNameWithUnicode = "u{134}ack"
print(playerName)
print(playerNameWithQuotes)
print(playerNameWithUnicode)

When you run the program, the output will be:

Jack
"Jack"
Ĵack

See Swift characters and strings to learn more about characters and strings declaration, operations and examples.

In addition to this data types, there are also other advanced data types in Swift like tupleoptionalrangeclassstructure etc. which you will learn in later chapters.


Things to remember

1. Since Swift is a type inference language, variables or constants can automatically infer the type from the value stored. So, you can skip the type while creating variable or constant. However you may consider writing the type for readability purpose but it’s not recommended.

Example 9: Type inferred variable/constant

let playerName = "Jack"
print(playerName)

Swift compiler can automatically infer the variable to be of String type because of its value.

2. Swift is a type safe language. If you define a variable to be of certain type you cannot change later it with another data type.

 

Example 10: Swift is a type safe language

let playerName:String
playerName = 55 //compile time error

The above code will create an error because we already specified that variable playerName is going to be a String. So we cannot store a Integer number in it.

 

Swift programming for Beginners – Swift Data Types

 

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!