Lesson 1 of 4

Swift Fundamentals

Master the Swift programming language syntax, data types, control flow, and functional programming concepts essential for iOS development.

30 minutes

Swift Fundamentals

Swift is a powerful and intuitive programming language created by Apple for iOS, macOS, and other Apple platforms.

Why Swift?

  • Modern Syntax: Clean, expressive code that's easy to read and write
  • Type Safety: Catch errors at compile time, not runtime
  • Performance: Fast execution comparable to C-based languages
  • Interoperability: Works seamlessly with Objective-C code

Variables and Constants

Swift uses var for variables and let for constants:

var userName = "Sarah"  // Can be changed
let maxRetries = 3      // Cannot be changed

Data Types

Swift provides strong typing with inference:

  • Int: Whole numbers (42, -17, 0)
  • Double/Float: Decimal numbers (3.14, -0.5)
  • String: Text ("Hello, Swift!")
  • Bool: True or false values
  • Array: Ordered collections [1, 2, 3]
  • Dictionary: Key-value pairs ["name": "Sarah"]

Optionals

Swift's killer feature for handling nil values safely:

var optionalName: String? = "Alice"
optionalName = nil // This is allowed
  • Use ? to declare optional types
  • Use ! for forced unwrapping (use carefully)
  • Use if let or guard let for safe unwrapping

Control Flow

Swift provides familiar control structures with powerful pattern matching:

  • if/else: Conditional logic
  • switch: Pattern matching (more powerful than other languages)
  • for-in: Iterate over collections
  • while: Loop while condition is true

Functions

Functions are first-class citizens in Swift:

func greet(person: String) -> String {
    return "Hello, \(person)!"
}

Best Practices

  • Prefer let over var for immutability
  • Use optionals to explicitly handle nil values
  • Leverage type inference but be explicit when needed
  • Follow Swift naming conventions (camelCase)

Code Example

// Variables and Constants
let appName = "MyFirstApp"
var userScore = 0

// Data Types
let age: Int = 28
let price: Double = 19.99
let isActive: Bool = true
let items: [String] = ["Apple", "Banana", "Orange"]

// Optionals
var email: String? = "user@example.com"
if let unwrappedEmail = email {
    print("Email: \(unwrappedEmail)")
} else {
    print("No email provided")
}

// Functions
func calculateTotal(price: Double, quantity: Int) -> Double {
    return price * Double(quantity)
}

let total = calculateTotal(price: 9.99, quantity: 3)
print("Total: $\(total)") // Output: Total: $29.97

// Control Flow
for item in items {
    print("Item: \(item)")
}

// Switch with pattern matching
switch userScore {
case 0:
    print("Just starting!")
case 1...10:
    print("Getting better!")
default:
    print("Doing great!")
}