Variables and constants in Swift store values, and those values have specific types.
Data types define what kind of data can be stored, how much memory it occupies, and what operations can be performed on it.
Swift is a "type-safe" language, which means you cannot accidentally assign a string to a variable that expects an integer.
Swift provides all the fundamental data types you would expect in a modern programming language.
Here are the most common ones:
Int: Used for whole numbers (e.g., 10, -5, 0).Double: Used for floating-point numbers with high precision (e.g., 3.14159).Float: Used for floating-point numbers with lower precision.Bool: Used for true or false values (true, false).String: Used for a sequence of characters (e.g., "Hello").Character: Used for a single character (e.g., "A").While Swift usually infers the type automatically, you can explicitly state it.
let age: Int = 25 let pi: Double = 3.14159265 let isLoggedIn: Bool = true let initial: Character = "A" let name: String = "Akash"print("Name: \(name), Age: \(age)")
Double represents a 64-bit floating-point number, while Float represents a 32-bit floating-point number.
Because Double has more precision (it can hold more decimal places), Swift will always infer Double by default if you don't specify the type.
If you strictly want to save memory and precision isn't critical, you can explicitly annotate a variable as Float.
Because Swift is type-safe, it performs type checks when compiling your code.
If a variable is defined as an Int, you cannot store a String inside it later.
var count = 5 // count = "Five" // This will cause a compiler error!
This behavior prevents many common bugs that occur in loosely typed languages.
Which data type is used to store text in Swift?