Swift Data Types

Swift Data Types

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.


Core Data Types

Swift provides all the fundamental data types you would expect in a modern programming language.

Here are the most common ones:


Explicit Data Types Example

While Swift usually infers the type automatically, you can explicitly state it.

Explicit Data Types:

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)")


Float vs Double

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.


Type Safety

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.

Type Safety Error:

var count = 5
// count = "Five" // This will cause a compiler error!

This behavior prevents many common bugs that occur in loosely typed languages.


Exercise

Which data type is used to store text in Swift?