Lesson 4Swift Basics

Type Safety

Type Safety in Swift

Swift won't let you mix incompatible types. This catches bugs before your code even runs!

Why Type Safety Matters

  • Catches errors early - At compile time, not runtime
  • More predictable - You know exactly what type you're working with
  • Better code - Forces you to think about your data

Type Mismatches

Swift will give you an error if you try to:

  • Assign a String to an Int variable
  • Add an Int and a Double directly
  • Compare different types

Type Conversion

When you need to mix types, explicitly convert them:

  • Double(intValue) - Int to Double
  • Int(doubleValue) - Double to Int (truncates)
  • String(number) - Number to String
main.swift
// Type annotations - explicitly specify the type
let name: String = "Alex"
let age: Int = 12
let height: Double = 4.5
let isAwesome: Bool = true

// Swift prevents type mismatches
var score: Int = 100
// score = "high" // Error! Can't assign String to Int
// score = 99.5   // Error! Can't assign Double to Int

// You can't mix different types in operations
let a: Int = 5
let b: Double = 3.14
// let result = a + b // Error! Different types

// Convert types when needed
let result = Double(a) + b  // Convert Int to Double
print(result) // 8.14

let roundedDown = Int(3.9)  // Converts to 3
print(roundedDown)

// Type checking
let mystery = 42
print(type(of: mystery)) // Int

let decimal = 42.0
print(type(of: decimal)) // Double

Try It Yourself!

Create an Int and a Double, then add them together using type conversion. What happens when you convert 3.9 to an Int?