Swift Data Types
Understanding different types of data in Swift
π·οΈ What are Swift Data Types?
Data types in Swift define what kind of data a variable can store. Swift provides built-in types like Int for numbers, String for text, Bool for true/false values, and Double for decimal numbers.
let age: Int = 25
let name: String = "Swift"
let isActive: Bool = true
Basic Swift Data Types
Int
Whole numbers (integers)
let count: Int = 42
let negative: Int = -10
String
Text and characters
let message: String = "Hello"
let emoji: String = "π"
Bool
True or false values
let isReady: Bool = true
let isComplete: Bool = false
Double
Decimal numbers
let price: Double = 19.99
let pi: Double = 3.14159
πΉ Integer Types
Swift provides several integer types for different ranges:
// Standard integer type
let age: Int = 25
let year: Int = 2024
// Specific bit-width integers
let smallNumber: Int8 = 127 // -128 to 127
let mediumNumber: Int16 = 32767 // -32,768 to 32,767
let largeNumber: Int64 = 9223372036854775807
// Unsigned integers (positive only)
let positiveOnly: UInt = 100
let smallPositive: UInt8 = 255 // 0 to 255
print("Age: \(age)")
print("Year: \(year)")
Output:
Age: 25
Year: 2024
πΉ Floating-Point Types
Use Float and Double for decimal numbers:
// Double (64-bit, more precise)
let preciseNumber: Double = 3.141592653589793
let price: Double = 29.99
// Float (32-bit, less precise)
let simpleFloat: Float = 3.14
let temperature: Float = 98.6
// Swift prefers Double by default
let defaultDecimal = 2.5 // This is Double
print("Price: $\(price)")
print("Temperature: \(temperature)Β°F")
Output:
Price: $29.99
Temperature: 98.6Β°F
πΉ String Type
Strings store text and support Unicode characters:
// Basic strings
let firstName: String = "John"
let lastName: String = "Doe"
// String interpolation
let fullName = "\(firstName) \(lastName)"
// Multi-line strings
let poem = """
Roses are red,
Violets are blue,
Swift is awesome,
And so are you!
"""
// Unicode and emojis
let greeting = "Hello π"
let flag = "πΊπΈ"
print(fullName)
print(greeting)
Output:
John Doe
Hello π
πΉ Boolean Type
Bool represents true or false values:
// Boolean literals
let isLoggedIn: Bool = true
let hasPermission: Bool = false
// Boolean from comparisons
let isAdult = age >= 18
let isWeekend = dayOfWeek == "Saturday" || dayOfWeek == "Sunday"
// Using booleans in conditions
if isLoggedIn {
print("Welcome back!")
} else {
print("Please log in")
}
// Boolean operations
let canAccess = isLoggedIn && hasPermission
print("Can access: \(canAccess)")
Output:
Welcome back!
Can access: false
πΉ Character Type
Character represents a single character:
// Single characters
let firstLetter: Character = "A"
let symbol: Character = "@"
let emoji: Character = "π"
// Building strings from characters
let chars: [Character] = ["H", "e", "l", "l", "o"]
let word = String(chars)
print("First letter: \(firstLetter)")
print("Word: \(word)")
Output:
First letter: A
Word: Hello