Swift Type Inference

How Swift automatically determines data types

🧠 What is Type Inference?

Type inference is Swift's ability to automatically determine the data type of a variable based on its initial value. You don't always need to explicitly specify types, making code cleaner and easier to write.


let name = "Swift"        // Inferred as String
let count = 42           // Inferred as Int
let price = 19.99        // Inferred as Double
                                    

Type Inference Examples

🔤

String Inference

Text values become String type

let message = "Hello"
// Type: String
🔢

Number Inference

Whole numbers become Int

let age = 25
// Type: Int
💫

Decimal Inference

Decimal numbers become Double

let pi = 3.14
// Type: Double
✅

Boolean Inference

true/false values become Bool

let isReady = true
// Type: Bool

🔹 Basic Type Inference

Swift automatically infers types from initial values:

// Swift infers these types automatically
let userName = "Alice"           // String
let userAge = 28                // Int
let userHeight = 5.6            // Double
let isStudent = false           // Bool
let grade = 'A'                 // Character

// You can still specify types explicitly if needed
let explicitString: String = "Hello"
let explicitInt: Int = 42

print("User: \(userName), Age: \(userAge)")
print("Height: \(userHeight), Student: \(isStudent)")

Output:

User: Alice, Age: 28

Height: 5.6, Student: false

🔹 Numeric Type Inference

Swift has specific rules for inferring numeric types:

// Integer literals are inferred as Int
let wholeNumber = 100           // Int
let negativeNumber = -50        // Int

// Decimal literals are inferred as Double
let decimalNumber = 3.14        // Double
let scientificNotation = 1.25e2 // Double (125.0)

// You can force Float type explicitly
let floatNumber: Float = 3.14   // Float

// Hexadecimal, octal, and binary literals
let hexNumber = 0xFF            // Int (255)
let octalNumber = 0o377         // Int (255)
let binaryNumber = 0b11111111   // Int (255)

print("Decimal: \(decimalNumber)")
print("Hex: \(hexNumber)")

Output:

Decimal: 3.14

Hex: 255

🔹 Collection Type Inference

Swift can infer types for arrays and dictionaries:

// Array type inference
let numbers = [1, 2, 3, 4, 5]           // [Int]
let names = ["Alice", "Bob", "Charlie"]  // [String]
let prices = [9.99, 19.99, 29.99]      // [Double]

// Dictionary type inference
let ages = ["Alice": 25, "Bob": 30]     // [String: Int]
let scores = ["Math": 95.5, "Science": 88.0] // [String: Double]

// Mixed types require explicit annotation
let mixedArray: [Any] = [1, "Hello", true]

print("First name: \(names[0])")
print("Alice's age: \(ages["Alice"] ?? 0)")

Output:

First name: Alice

Alice's age: 25

🔹 Function Return Type Inference

Swift can infer return types for simple functions:

// Return type inferred as Int
func addNumbers(a: Int, b: Int) -> Int {
    return a + b
}

// Return type inferred from the return statement
func greetUser(name: String) -> String {
    return "Hello, \(name)!"
}

// Return type inferred as Bool
func isEven(number: Int) -> Bool {
    return number % 2 == 0
}

let sum = addNumbers(a: 5, b: 3)
let greeting = greetUser(name: "Swift")
let evenCheck = isEven(number: 4)

print("Sum: \(sum)")
print(greeting)
print("Is 4 even? \(evenCheck)")

Output:

Sum: 8

Hello, Swift!

Is 4 even? true

🔹 When to Use Explicit Types

Sometimes you need to specify types explicitly:

Use explicit types when:

  • Clarity: Make code more readable
  • Precision: Need specific numeric types
  • Empty Collections: Arrays/dictionaries with no initial values
  • Protocols: Working with protocol types
// Explicit types for clarity
let userID: Int = 12345
let apiKey: String = "abc123"

// Specific numeric types
let temperature: Float = 98.6
let distance: Double = 1000.0

// Empty collections need explicit types
var emptyNumbers: [Int] = []
var emptyDictionary: [String: Int] = [:]

// Protocol types
let items: [Any] = [1, "Hello", true]

print("User ID: \(userID)")
print("Temperature: \(temperature)°F")

Output:

User ID: 12345

Temperature: 98.6°F

🧠 Test Your Knowledge

What type will Swift infer for: let price = 29.99