English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Swift Data Types

In this tutorial, you will learn about the different data types supported by the Swift programming language and use it when creating variables or constants.

Data types are the types of data (values) that can be stored in variables or constants. For example, in the articleSwift Variables and ConstantsYou have created a variable and a constant to store string data in memory.

The data can be text/A string ("Hello") or a number(12.45) can also be a bit (0&1Defining data types ensures that only the defined data types are stored.

Let's look at a scenario:

Assuming you want to create a game. Since most games display high scores and player names after the game is over, you need to store these two pieces of data for the game.

High score (highScore) is a number (e.g., 59),player's name (playerName) is a string (e.g., Jack). You can create two variables or constants to store data.

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

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

Here, we declare an Int type variable HighScore that stores the value59. And a string type variable playerName to store the value Jack.

But if you perform the following operation:

var highScore: Int = "Jack"

You will get a compile-time error, throwing Cannot convert 'String' type value to specified 'Int' type.

This is because you declared highScore to store integer values, but you placed a string in it. This error ensures that highScore can only store a number and cannot store the player's name.

Size of data type

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

The size of Type is measured in bits, and it can store at most 2bits. If you understand Bit (bit), you can imagine it as a 0 or1values.

Therefore, forType size = 1 bit, then it can store at most 2 1 = 2, two values: 0 or 1. Therefore, the letter program's1The binary system can interpret 0 as a/,1Interpreted as b/1.0.

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

Similarly, the binary system can store at most2 2 = 4values: (00,01,10,11), each combination can be represented as:

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

For the binary system, it can store at most2 n valuesValue.

Swift data types

The following lists the most commonly used data types in Swift:

Boolean type (Bool)

  • Variables declared as Bool type/Constants can only store two values, true or false.

  • Default value: false

  • When handling if-It is often used in the else statement. You can refer to the article Swift if else.

Example1: Boolean data type

let result: Bool = true
print(result)

When running the program, the output is:

true

Integer type (Integer)

  • Variables declared as integer types/Constants can store positive and negative numbers, including zero, without a fractional part.

  • Default value: 0

  • Size:32/64bit depends on the platform type.

  • Value range:-2,147,483,648 to 2,147,483,647(32bit platform)
    -9223372036854775808 to 9223372036854775807(64bit platform)

  • There are many variants of the Integer type, such as UInt and Int8, Int16. The most commonly used is Int.

  • If you need to specify the variable/the size of integers that constants can accommodate/types, such as UInt, Int8, Int16and more specifically store it, we will introduce these below.

Example2: integer data type

var highScore: Int = 100
print(highScore)
highScore = -100
print(highScore)

When running the program, the output is:

100
-100

In the above example, we declared a variable highScore of type Int. First, we assigned it a value of100, so print (highScore) outputs to the screen100.

Later, we use the assignment operator highScore =-100, so we change the value to -100, so when printing (highScore) output-100.

Let's take a look at some variants of the Int type in Swift.

Int8(integer)

  • is a variant of integer types that can store both positive and negative numbers.

  • Default value: 0

  • Size:8bits

  • range:-128 to 127

one Int8Integers can store a total of2 8 =(256) values. That is, it can store from 255between numbers.

but because Int8 including positive and negative numbers, we can store from-128to127of numbers, including 0, totaling256values or numbers.

var highScore: Int8 = -128//correct
highScore = 127 //correct
highScore = 128 //error
highScore = -129 //error

You can also use Swift function The built-in .min and .max functions can find the maximum and minimum values that the type can store.

Example3: maximum and minimum Int8Data type

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

When running the program, the output is:

-128
127

UInt (unsigned integer)

  • Variants of integer types called UInt (unsigned integers) can only store unsigned numbers (positive numbers or zero).

  • Default value: 0

  • Size:32/64bit depends on the platform type.

  • range: 0 to 4294967295(32bit platform)
    0 to 18446744073709551615(64bit platform)

Example4: UInt data type

var highScore: UInt = 100
highScore = -100 //Compile-time error occurs when trying to perform the following operation

The above code will throw a compile-time error because unsigned integers can only store 0 or positive values. Trying to store a negative value in an unsigned integer will result in an error.

Float (floating-point number)

  • Variables or constants declared as floating-point can store numbers with decimal points or decimal points.

  • Default value: 0.0

  • Size:32bit floating-point numbers.

  • range:1.2 * 10 -38to3.4 * 10 38(~6bit numbers)

Example5: floating-point data type

let highScore: Float = 100.232
print(highScore)

When running the program, the output is:

100.232

Double (double-precision floating-point number)

  • Variables declared as Double type/Constants will also store numbers with decimals or decimal points as Float, but with a larger decimal point than Float supports.

  • Default value: 0.0

  • Size:64A floating-point number. (Therefore, variables of type Double can store numbers with decimals or decimal points larger than those supported by Float)

  • range:2.3×10 -308~,1.7 * 10 308(~15bit)

Example6: double precision data type

let highScore:Double = 100.232321212121
print(highScore)

When running the program, the output is:

100.232321212121

Character (character)

  • Declare a variable as Character type/Constants can store single-character string literals.

  • You can use the escape sequence \u{n} (Unicode character, n is hexadecimal) in Swift to use emoji or characters in languages other than English.

Example7: character data type

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

When running the program, the output is:

J
Ĵ

String (string)

  • Variables or constants declared as String type can store a set of characters.

  • Default value:""(empty string)

  • It is a value type.

  • You can use for-to iterate through strings in a loop.referenceSwift for-in loop.

  • Swift also supports some special escape sequences that can be used in strings. For example,

    • \0 (null character),

    • \\ (a normal backslash \),

    • \t (tab),

    • \v (vertical tab),

    • \r (carriage return),

    • \" (double quotes),

    • \' (apostrophe), and

    • \u{n} (unicode string, n is represented in hexadecimal).

Example8: string data type

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

When running the program, the output is:

Jack
"Jack"
Ĵack

Please refer toSwift characters and strings,to learn more about character and string declarations, operations, and examples.

In addition to this data type, Swift also has other advanced data types, such as tuple,optional,range,class,structure You will learn about them in the following chapters.

Things to remember

1Since Swift is a type inference language, variables or constants can automatically infer types from the stored values. Therefore, you can omit the type when creating variables or constants. However, you may consider writing types for readability, but it is not recommended to do so.

Example9: Variables with type inference/Constants

let playerName = "Jack"
print(playerName)

The Swift compiler can automatically infer that the variable is of type String based on its value.

2. Swift is a type-safe language. If you define a variable of a certain type, you cannot use other data types to change it later.

Example10Swift is a type-safe language

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

The above code will produce an error because we have specified that the variable playerName will be of type String. Therefore, we cannot store an integer in it.