Menu
Coddy logo textTech

Declare A Function

Part of the Fundamentals section of Coddy's Swift journey — lesson 51 of 86.

A function is a reusable block of code that performs a specific task. Instead of writing the same code multiple times, you define it once in a function and call it whenever needed.

In Swift, you declare a function using the func keyword, followed by the function name and parentheses:

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

sayHello()  // Output: Hello!
sayHello()  // Output: Hello!

The code inside the curly braces { } is the function body—it runs each time you call the function. To call a function, simply write its name followed by parentheses.

Functions help organize your code and make it more readable. If you need to change how something works, you only update it in one place rather than everywhere it's used.

func greetUser() {
    print("Welcome!")
    print("Glad to have you here.")
}

greetUser()

A function can contain any code you've learned so far—variables, loops, conditionals—all bundled together under a meaningful name.

challenge icon

Challenge

Easy
Write a function printGreeting that takes no parameters and returns a greeting message.

The function should return the string "Hello, Swift!" exactly as shown.

Parameters:

  • None

Returns: The string "Hello, Swift!" (String)

Cheat sheet

A function is a reusable block of code that performs a specific task. You define it once and call it whenever needed.

Declare a function using the func keyword, followed by the function name and parentheses:

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

sayHello()  // Output: Hello!

The code inside the curly braces { } is the function body. To call a function, write its name followed by parentheses.

A function can contain variables, loops, conditionals, and other code:

func greetUser() {
    print("Welcome!")
    print("Glad to have you here.")
}

greetUser()

Try it yourself

func printGreeting() -> String {
    // Write code here
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals