Use Integers in Swift
Written by Team Kodeco
Written by Team Kodeco
Integers are whole numbers, positive or negative, without a decimal point. In Swift, integers come in two sizes:
- Int: The native size of integers for the platform (and what you should use most of the time).
- UInt: The same size but can only represent positive integers.
To declare an integer variable, use the keyword var
or let
followed by the variable name and assign it a value.
var age: Int = 25
let weight: UInt = 150
let favoriteNumber = 42 // Using type inference
print(type(of: favoriteNumber)) // Prints Int
You can also perform mathematical operations with integers such as addition, subtraction, multiplication and division.
var a = 5
var b = 2
var sum = a + b //7
var difference = a - b //3
var product = a * b //10
var quotient = a / b //2
It’s also possible to use shorthand operators to modify the value of a variable by a specific amount:
var value = 5
value += 2 // value is now 7
value -= 3 // value is now 4
value *= 2 // value is now 8
value /= 2 // value is now 4
Prev chapter
9.
Understand the Differences Between Value Types & Reference Types
Next chapter
2.
Use Floating-Point Numbers in Swift