Lesson 9Swift Basics
Numbers
Numbers in Swift
Swift provides different types for working with numbers. Let's explore integers and floating-point numbers!
Integer Types
IntMost common, for whole numbers
UIntUnsigned (positive only)
Floating-Point Types
Double64-bit, more precision (default)
Float32-bit, less precision
Useful Functions
abs()Absolute value
max()Maximum value
min()Minimum value
Random Numbers
Use Int.random(in: 1...100) to get a random number between 1 and 100!
main.swift
// Integers - whole numbers
let age: Int = 12
let score = 100 // Inferred as Int
let negative = -50
// Large numbers with underscores for readability
let million = 1_000_000
let billion = 1_000_000_000
// Different number formats
let binary = 0b1010 // Binary: 10
let octal = 0o12 // Octal: 10
let hex = 0xFF // Hexadecimal: 255
// Floating-point numbers
let pi: Double = 3.14159265359
let temperature = 98.6 // Inferred as Double
let price: Float = 9.99 // Less precision
// Number limits
print("Int max: \(Int.max)")
print("Int min: \(Int.min)")
// Math operations
let sum = 10 + 5 // 15
let product = 10 * 5 // 50
let quotient = 10.0 / 3.0 // 3.333...
let remainder = 10 % 3 // 1
// Useful functions
print(abs(-5)) // 5 (absolute value)
print(max(3, 7, 2)) // 7 (maximum)
print(min(3, 7, 2)) // 2 (minimum)
// Random numbers
let random = Int.random(in: 1...100)
print("Random: \(random)")
let dice = Int.random(in: 1...6)
print("Dice roll: \(dice)")Try It Yourself!
Create a program that calculates and prints the average of three numbers. Then generate a random dice roll!