Design+Code logo

Quick links

Suggested search

1. Understanding the Basics

A. What are Functions?

i. Definition: A function is a self-contained block of code that performs a specific task. Think of functions as mini-programs within your app that you can call whenever you need to perform that task.

ii. Real-world analogy: Functions are like recipes. A recipe has a name, a list of ingredients (inputs), steps to follow (the code), and a finished dish (output). Once you write a recipe, you can use it whenever you want without rewriting all the steps.

iii. Benefits: Functions allow you to:

  • Organize code into manageable chunks
  • Reuse code without copying and pasting
  • Make your code more readable and maintainable

B. Why Functions are Important

i. Code organization: Functions help you organize your code logically, separating different tasks into named blocks.

ii. Reusability: Write once, use many times - reducing duplication in your code.

iii. Abstraction: Functions let you hide complex operations behind simple names, making your code more readable.

iv. Testability: Individual functions can be tested separately, making it easier to ensure your code works correctly.

C. Function Syntax in Swift

i. Basic structure:

func functionName(parameterName: ParameterType) -> ReturnType {
    // Function body - code that runs when the function is called
    return someValue
}

ii. The parts explained:

  • func: Keyword that tells Swift you're declaring a function
  • functionName: The name you give your function (use camelCase by convention)
  • parameterName: ParameterType: Input values the function needs to do its job
  • -> ReturnType: What type of value the function will give back when it's done
  • return someValue: The actual value returned to the caller

2. Creating and Calling Functions

A. Basic Function Declaration

i. Functions without parameters or return values:

func sayHello() {
    print("Hello, world!")
}

// Call the function
sayHello() // Prints: Hello, world!

ii. Functions with a return value:

func giveMeFive() -> Int {
    return 5
}

let number = giveMeFive() // number equals 5

iii. Functions that perform a task but don't return a value:

func printDivider() {
    print("----------")
}

printDivider() // Prints: ----------

B. Function Parameters

i. Single parameter:

func greet(name: String) {
    print("Hello, \(name)!")
}

greet(name: "John") // Prints: Hello, John!

ii. Multiple parameters:

func introduce(name: String, age: Int) {
    print("This is \(name) and they are \(age) years old.")
}

introduce(name: "Emma", age: 28) // Prints: This is Emma and they are 28 years old.

iii. Argument labels:

// Using different external (argument) and internal (parameter) names
func greet(person name: String) {
    print("Hello, \(name)!")
}

greet(person: "Taylor") // Prints: Hello, Taylor!

// Omitting argument labels with _
func greet(_ name: String) {
    print("Hello, \(name)!")
}

greet("Taylor") // Cleaner call without argument label

C. Return Values

i. Returning simple values:

func add(a: Int, b: Int) -> Int {
    return a + b
}

let sum = add(a: 5, b: 3) // sum equals 8

ii. Returning multiple values using tuples:

func getMinMax(array: [Int]) -> (min: Int, max: Int) {
    let sortedArray = array.sorted()
    return (sortedArray.first!, sortedArray.last!)
}

let bounds = getMinMax(array: [8, 3, 9, 4, 1])
print("Min is \(bounds.min) and max is \(bounds.max)")
// Prints: Min is 1 and max is 9

iii. Optional return values:

func findIndex(of value: Int, in array: [Int]) -> Int? {
    for (index, item) in array.enumerated() {
        if item == value {
            return index
        }
    }
    return nil // Not found
}

if let index = findIndex(of: 5, in: [1, 7, 5, 9]) {
    print("Found at position \(index)")
} else {
    print("Not found")
}

3. Advanced Function Features

A. Default Parameter Values

i. Setting defaults:

func greet(name: String, greeting: String = "Hello") {
    print("\(greeting), \(name)!")
}

greet(name: "Bob") // Uses default: Hello, Bob!
greet(name: "Alice", greeting: "Hola") // Override default: Hola, Alice!

ii. Making parameters optional with defaults:

func createProfile(name: String, bio: String = "", age: Int = 0) {
    // Only name is required, others are optional
    print("Created profile for \(name)")
}

createProfile(name: "Jamie") // Only providing required parameter

B. Variadic Parameters

i. Accepting multiple values of the same type:

func calculateAverage(of numbers: Double...) -> Double {
    var total = 0.0
    for number in numbers {
        total += number
    }
    return numbers.isEmpty ? 0 : total / Double(numbers.count)
}

let avg1 = calculateAverage(of: 5.0, 3.0, 9.5, 2.5) // 5.0
let avg2 = calculateAverage(of: 10.0) // 10.0

ii. Combining with normal parameters:

func printTeam(teamName: String, members: String...) {
    print("Team \(teamName) has \(members.count) members:")
    for member in members {
        print("- \(member)")
    }
}

printTeam(teamName: "Swift Coders", members: "Alice", "Bob", "Charlie")

C. In-out Parameters

i. Modifying parameters:

func swapValues(_ a: inout Int, _ b: inout Int) {
    let temporaryA = a
    a = b
    b = temporaryA
}

var first = 5
var second = 10
swapValues(&first, &second)
print("first is now \(first), second is now \(second)")
// Prints: first is now 10, second is now 5

ii. When to use in-out:

  • When you need to modify the original variable, not just its value
  • For simple operations that logically modify an existing value instead of returning a new one
  • When implementing reference semantics with value types

4. Function Types

A. Functions as Types

i. Function type syntax:

// A function type that takes an Int and returns a Bool
var checkFunction: (Int) -> Bool

// Assign an actual function to this variable
func isEven(number: Int) -> Bool {
    return number % 2 == 0
}

checkFunction = isEven

ii. Using function variables:

// Now we can call the function through the variable
let result = checkFunction(6) // result is true

B. Functions as Parameters

i. Passing functions to other functions:

func printResult(_ number: Int, using operation: (Int) -> Int) {
    let result = operation(number)
    print("The result is \(result)")
}

func square(number: Int) -> Int {
    return number * number
}

func double(number: Int) -> Int {
    return number * 2
}

printResult(5, using: square) // Prints: The result is 25
printResult(5, using: double) // Prints: The result is 10

ii. Real-world example - sorting with custom comparators:

let names = ["Chris", "Alex", "Barry", "Diana"]

// Pass a function to sort() that determines the sorting order
let sortedNames = names.sorted(by: { (s1: String, s2: String) -> Bool in
    return s1.count < s2.count
})
// sortedNames is ["Alex", "Chris", "Barry", "Diana"] (sorted by length)

C. Returning Functions

i. Creating function factories:

func makeAdder(amount: Int) -> (Int) -> Int {
    func adder(number: Int) -> Int {
        return number + amount
    }
    return adder
}

let addFive = makeAdder(amount: 5)
let result = addFive(10) // result equals 15

ii. Use cases for returning functions:

  • Creating customized functions on demand
  • Implementing strategy patterns
  • Setting up behavior that needs configuration

5. Closures

A. Understanding Closures

i. Definition: Closures are self-contained blocks of functionality that can be passed around and used in your code, similar to functions but with a more compact syntax.

ii. Relationship to functions: Closures are essentially unnamed functions. Every function is actually a closure, but not every closure is a function.

iii. Basic closure syntax:

// A closure that takes two Ints and returns an Int
let addClosure: (Int, Int) -> Int = { (a: Int, b: Int) -> Int in
    return a + b
}

// Using the closure
let sum = addClosure(5, 3) // sum equals 8

B. Closure Syntax and Shorthand

i. Full syntax:

let multiply: (Int, Int) -> Int = { (a: Int, b: Int) -> Int in
    return a * b
}

ii. Type inference:

// Swift can infer parameter and return types
let multiply: (Int, Int) -> Int = { a, b in
    return a * b
}

iii. Implicit return:

// Single-expression closures can omit 'return'
let multiply: (Int, Int) -> Int = { a, b in a * b }

iv. Shorthand argument names:

// Use $0, $1, etc. instead of naming parameters
let multiply: (Int, Int) -> Int = { $0 * $1 }

v. Trailing closure syntax:

// When a closure is the last argument to a function
let numbers = [1, 2, 3, 4, 5]

// Without trailing closure
let doubled1 = numbers.map({ number in number * 2 })

// With trailing closure
let doubled2 = numbers.map { number in number * 2 }

// With shorthand arguments
let doubled3 = numbers.map { $0 * 2 }

C. Common Use Cases

i. Array operations:

let numbers = [1, 2, 3, 4, 5]

// Filter even numbers
let evenNumbers = numbers.filter { $0 % 2 == 0 }

// Transform each number
let squared = numbers.map { $0 * $0 }

// Reduce to a single value
let sum = numbers.reduce(0) { $0 + $1 }

ii. Completion handlers:

func fetchData(completion: (Data?) -> Void) {
    // Simulate network request
    DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
        let data = Data()
        completion(data)
    }
}

fetchData { data in
    if let data = data {
        print("Data received: \(data)")
    } else {
        print("No data received")
    }
}

iii. Animation and timing:

// UIKit animation with closure
UIView.animate(withDuration: 0.3) {
    someView.alpha = 0
}

6. Best Practices

A. Naming Conventions

i. Use verb phrases for functions:

// Good:
func calculateTotal() { }
func fetchUserData() { }
func isValid() -> Bool { }

// Avoid:
func userData() { } // Sounds like a property, not an action
func calculation() { } // Too vague

ii. Be descriptive about parameters:

// Good:
func move(from source: Point, to destination: Point) { }

// Avoid:
func move(a: Point, b: Point) { } // Not clear what a and b represent

iii. Be consistent with Swift's standard library:

  • Use get prefix for functions that return a value
  • Use is prefix for Boolean functions
  • Use camelCase for function and parameter names

B. Function Length and Responsibility

i. Single responsibility principle:

  • Each function should do one thing and do it well
  • If a function is doing multiple things, consider breaking it up

ii. Keep functions short:

  • Aim for functions that can be understood at a glance (generally under 20-30 lines)
  • Long functions are harder to understand, test, and maintain

iii. Example of refactoring:

// Too many responsibilities
func processUserData(user: User) {
    // Validate user input
    guard user.email.contains("@") else { return }
    guard user.name.count > 0 else { return }

    // Save to database
    database.save(user)

    // Send welcome email
    emailService.sendWelcome(to: user.email)
}

// Better approach - split into focused functions
func validateUser(_ user: User) -> Bool {
    return user.email.contains("@") && user.name.count > 0
}

func saveUser(_ user: User) {
    database.save(user)
}

func sendWelcomeEmail(to email: String) {
    emailService.sendWelcome(to: email)
}

func processUserData(user: User) {
    guard validateUser(user) else { return }
    saveUser(user)
    sendWelcomeEmail(to: user.email)
}

C. Documentation

i. Use comments to explain "why", not "what":

// Good:
// Delay processing by 100ms to prevent API rate limiting
delay(milliseconds: 100)

// Avoid:
// Delays by 100ms
delay(milliseconds: 100)

ii. Use Swift's documentation comments:

/// Calculates the average of an array of numbers.
/// - Parameter numbers: The numbers to average
/// - Returns: The average value, or 0 if the array is empty
func average(of numbers: [Double]) -> Double {
    guard !numbers.isEmpty else { return 0 }
    let sum = numbers.reduce(0, +)
    return sum / Double(numbers.count)
}

iii. Document edge cases and assumptions:

/// Divides two numbers.
/// - Parameters:
///   - dividend: The number to be divided
///   - divisor: The number to divide by
/// - Returns: The result of the division
/// - Warning: Will crash if divisor is zero
func divide(_ dividend: Double, by divisor: Double) -> Double {
    return dividend / divisor
}

7. Practice Exercises

A. Basic Function Creation

i. Exercise 1: Create a function that takes a person's name and age and prints a greeting message.

func greetPerson(name: String, age: Int) {
    print("Hello \(name), you are \(age) years old!")
}

greetPerson(name: "Sarah", age: 29)

B. Functions with Return Values

i. Exercise 2: Write a function that calculates the area of a rectangle.

func calculateRectangleArea(width: Double, height: Double) -> Double {
    return width * height
}

let area = calculateRectangleArea(width: 5.0, height: 3.0)
print("The area is \(area) square units")

C. Working with Closures

i. Exercise 3: Use the map function with a closure to convert an array of names to uppercase.

let names = ["john", "sarah", "mike", "emma"]
let uppercasedNames = names.map { $0.uppercased() }
print(uppercasedNames) // ["JOHN", "SARAH", "MIKE", "EMMA"]

8. Summary

Functions are fundamental building blocks in Swift that allow you to:

  • Break down complex tasks into smaller, reusable pieces
  • Create clear, organized, and maintainable code
  • Pass behavior around in your app
  • Build abstractions that hide complexity

Starting with basic functions, you can gradually incorporate more advanced features like:

  • Multiple parameters and return values
  • Default parameter values
  • In-out parameters
  • Functions as types
  • Closures for more concise code

Remember that good function design is about clarity and focus. Each function should have a single, well-defined purpose with a descriptive name that clearly communicates what it does.

As you become more comfortable with functions, you'll find they are one of Swift's most powerful features for writing clean, modular, and reusable code.

Learn with videos and source files. Available to Pro subscribers only.

Purchase includes access to 50+ courses, 320+ premium tutorials, 300+ hours of videos, source files and certificates.

BACK TO

Optionals

Templates and source code

Download source files

Download the videos and assets to refer and learn offline without interuption.

check

Design template

check

Source code for all sections

check

Video files, ePub and subtitles

Videos

Assets

1

Building Your iOS Development Foundation

Master the fundamentals of Swift programming with hands-on examples designed for beginners and experienced developers alike

2

SwiftUI Print Debugging

Print debugging: Unlock the invisible processes with strategic print statements that illuminate state changes, view lifecycles and data flow

18:04

3

Comments Documentation Waypoints

Transform your code from mysterious instructions to a comprehensive narrative with strategic comments that explain the why

22:02

4

Variables and Constants

Learn when and how to use variables and constants to write safer, more efficient SwiftUI code

11:37

5

Strings and Interpolation

Learn essential string operations in Swift: Build better iOS apps with efficient text handling techniques

13:22

6

Swift Operators: The Foundation of SwiftUI Logic

Building powerful iOS apps through the language of operations

5:34

7

Swift Unary Operators

Mastering the elegant simplicity of unary operators for cleaner, more expressive SwiftUI code that transforms your UI with minimal syntax

15:00

8

Swift Binary Operators

Master the two-operand symbols that transform complex interface logic into concise, readable declarations

3:36

9

Arithmetic Operators

Learn how to implement and optimize arithmetic operations in SwiftUI, from basic calculations to complex mathematical interfaces

6:11

10

If-Else and Comparison Operators

Building Dynamic SwiftUI: Mastering If-Else and Comparison Operators

12:32

11

Logical Operators

Master SwiftUI's logical operators: Building intelligent iOS apps with robust decision-making systems

6:03

12

Ternary Operators

Use the power of Swift's ternary conditional operator to create dynamic, responsive interfaces with minimal code in SwiftUI

6:22

13

Blocks and Scope

A comprehensive guide to writing clean, organized code through proper variable management and state control

10:22

14

Swift Collections: Arrays, Sets, and Dictionaries Overview

Organize Your Data Effectively: Learn How to Choose and Optimize the Perfect Collection Type for Your SwiftUI Applications

7:00

15

Swift Arrays

Organize, transform, and display your data with Swift's most essential collection structure

8:54

16

Swift Sets

Mastering Unique Collections with Fast Lookups and Powerful Operations

11:03

17

Swift Dictionaries

Master Swift's key-value collection type with practical examples for efficient data storage, retrieval, and transformation in SwiftUI apps

18

For-Loops and Range

For-Loops and Ranges: Learn how to repeat code efficiently and work with sequences of numbers in Swift

19

Optionals

Optionals in Swift: Understanding Swift's Safety System for Handling Missing Values

20

Functions

Functions in Swift: Building Reusable Code Blocks to Organize and Streamline Your App

Meet the instructor

We all try to be consistent with our way of teaching step-by-step, providing source files and prioritizing design in our courses.

Sourasith Phomhome

UI Designer

Designer at Design+Code

icon

20 courses - 78 hours

course logo

Master Agentic Workflows

In this course, you’ll learn how to add agents to your workflows. An agent workflow is more than just a simple automation. Instead of following a fixed script, agents can make decisions, adjust to changes, and figure out the best way to complete a task. We’ll start by exploring what MCP servers are and all the new possibilities they bring. Then, we’ll dive into agentic frameworks that make it easy to build flexible, helpful agents that can take care of your everyday tasks.

2 hrs

course logo

Design Multiple Apps with Figma and AI

In this course, you’ll learn to design multiple apps using Figma and AI-powered tools, tackling a variety of real-world UI challenges. Each week, a new episode will guide you through a different design, helping you master essential UI/UX principles and workflows

4 hrs

course logo

SwiftUI Fundamentals Handbook

A comprehensive guide to mastering Swift programming fundamentals, designed for aspiring iOS developers. This handbook provides a structured approach to learning Swift's core concepts, from basic syntax to advanced programming patterns. Through carefully sequenced chapters, readers will progress from essential programming concepts to object-oriented principles, building a solid foundation for SwiftUI development. Each topic includes practical examples and clear explanations, ensuring a thorough understanding of Swift's capabilities. This handbook serves as both a learning resource and a reference guide, covering fundamental concepts required for modern iOS development. Topics are presented in a logical progression, allowing readers to build their knowledge systematically while gaining practical programming skills.

2 hrs

course logo

Design and Code User Interfaces with Galileo and Claude AI

In this course, you’ll learn how to use AI tools to make UI/UX design faster and more efficient. We’ll start with Galileo AI to create basic designs, providing a solid foundation for your ideas. Next, we’ll refine these designs in Figma to match your personal style, and finally, we’ll use Claude AI to turn them into working code—eliminating the need for traditional prototyping.

4 hrs

course logo

Build a React Native app with Claude AI

This comprehensive course explores the integration of cutting-edge AI tools into the React Native development workflow, revolutionizing the approach to mobile application creation. Participants will learn to leverage AI-powered platforms such as Claude and Locofy to expedite coding processes, enhance problem-solving capabilities, and optimize productivity.

14 hrs

course logo

Design and Prototype for iOS 18

Design and Prototype for iOS 18 is an immersive course that equips you with the skills to create stunning, user-friendly mobile applications. From mastering Figma to understanding iOS 18's latest design principles, you'll learn to craft two real-world apps - a Car Control interface and an AI assistant.

3 hrs

course logo

Master Responsive Layouts in Figma

Creating responsive layouts is a must-have skill for any UI/UX designer. With so many different devices and screen sizes, designing interfaces that look great and work well on all platforms is necessary. Mastering this skill will make you stand out in the field. In this course, we'll start from scratch to create this beautiful design using Figma. You'll learn how to make layouts that are easy to use and work well on any device. We'll cover key concepts and tools to help you master responsive design in Figma.

2 hrs

course logo

UI UX Design with Mobbin and Figma

Mobbin is a powerful tool for UI/UX designers seeking inspiration and innovative design solutions. This platform offers a vast collection of real-world mobile app designs, providing a treasure trove of UI elements and layouts.

2 hrs

course logo

3D UI Interactive Web Design with Spline

Learn to create 3D designs and UI interactions such as 3D icons, UI animations, components, variables, screen resize, scrolling interactions, as well as exporting, optimizing, and publishing your 3D assets on websites

3 hrs

course logo

Design and Prototype for iOS 17 in Figma

Crafting engaging experiences for iOS 17 and visionOS using the Figma design tool. Learn about Figma's new prototyping features, Dev Mode, variables and auto layout.

6 hrs

course logo

Design and Prototype Apps with Midjourney

A comprehensive course on transforming Midjourney concepts into interactive prototypes using essential design techniques and AI tools

8 hrs

course logo

iOS Design with Midjourney and Figma

Learn the fundamentals of App UI design and master the art of creating beautiful and intuitive user interfaces for mobile applications

1 hrs

course logo

UI Design for iOS, Android and Web in Sketch

Create a UI design from scratch using Smart Layout, Components, Prototyping in Sketch app

1 hrs

course logo

UI Design a Camera App in Figma

Design a dark, vibrant and curvy app design from scratch in Figma. Design glass icons, lens strokes and realistic buttons.

1 hrs

course logo

UI Design for iOS 16 in Sketch

A complete guide to designing for iOS 16 with videos, examples and design files

3 hrs

course logo

Prototyping in Figma

Learn the basics of prototyping in Figma by creating interactive flows from custom designs

1 hrs

course logo

UI Design Quick Websites in Figma

Learn how to design a portfolio web UI from scratch in Figma

1 hrs

course logo

UI Design Android Apps in Figma

Design Android application UIs from scratch using various tricks and techniques in Figma

2 hrs

course logo

UI Design Quick Apps in Figma

Design application UIs from scratch using various tricks and techniques in Figma

12 hrs

course logo

Figma Handbook

A comprehensive guide to the best tips and tricks in Figma

6 hrs