Lesson 40Functions

Functions Practice

Practice Projects

Let's put all our function knowledge together with these mini-projects!

Mini Projects

1. Calculator

Multiple operations, error handling

2. String Formatter

Default parameters, switch cases

3. Array Processor

Variadic + function parameter

4. Password Validator

Tuple returns, validation logic

5. Function Factory

Nested functions, returning functions

Skills Used

ParametersReturn ValuesDefault ParametersVariadicFunction TypesNested FunctionsTuple Returns

Module Complete!

Congratulations! You've mastered Swift Functions. You can now write clean, reusable code!

Next up: Closures - anonymous functions and more!

main.swift
// PROJECT 1: Calculator
func calculate(_ a: Double, _ b: Double,
               operation: String) -> Double? {
    switch operation {
    case "+": return a + b
    case "-": return a - b
    case "*": return a * b
    case "/":
        guard b != 0 else { return nil }
        return a / b
    default: return nil
    }
}

print(calculate(10, 5, operation: "+")!)  // 15.0
print(calculate(10, 5, operation: "/")!)  // 2.0

// PROJECT 2: String Formatter
func formatName(first: String, last: String,
                style: String = "full") -> String {
    switch style {
    case "full": return "\(first) \(last)"
    case "initials":
        return "\(first.prefix(1)). \(last.prefix(1))."
    case "last-first": return "\(last), \(first)"
    default: return "\(first) \(last)"
    }
}

print(formatName(first: "John", last: "Doe"))
print(formatName(first: "John", last: "Doe", style: "initials"))

// PROJECT 3: Array Processor
func processNumbers(_ numbers: Int...,
                   using transform: (Int) -> Int) -> [Int] {
    return numbers.map(transform)
}

let doubled = processNumbers(1, 2, 3, 4, 5) { $0 * 2 }
print(doubled)  // [2, 4, 6, 8, 10]

// PROJECT 4: Password Validator
func validatePassword(_ password: String) -> (valid: Bool, errors: [String]) {
    var errors: [String] = []

    if password.count < 8 {
        errors.append("Must be at least 8 characters")
    }
    if !password.contains(where: { $0.isNumber }) {
        errors.append("Must contain a number")
    }
    if !password.contains(where: { $0.isUppercase }) {
        errors.append("Must contain uppercase letter")
    }

    return (errors.isEmpty, errors)
}

let result = validatePassword("hello")
if !result.valid {
    print("Errors: \(result.errors)")
}

// PROJECT 5: Function Factory
func makeGreeting(language: String) -> (String) -> String {
    func english(_ name: String) -> String {
        return "Hello, \(name)!"
    }
    func spanish(_ name: String) -> String {
        return "¡Hola, \(name)!"
    }
    func french(_ name: String) -> String {
        return "Bonjour, \(name)!"
    }

    switch language {
    case "es": return spanish
    case "fr": return french
    default: return english
    }
}

let greetInSpanish = makeGreeting(language: "es")
print(greetInSpanish("Carlos"))  // ¡Hola, Carlos!

Challenge!

Create a mini text adventure game using functions: one for displaying choices, one for processing input, and nested functions for different rooms!