Swift Function Syntax šŸŽÆ

beginner
21 min

Swift Function Syntax šŸŽÆ

Welcome to the Swift Function Syntax tutorial! In this lesson, we'll explore the fundamentals of functions, their importance in Swift, and how to create, call, and master them. Let's get started!

What is a Function? šŸ“

In Swift, a function is a piece of reusable code that performs a specific task. Functions help us organize our code, making it cleaner, more efficient, and easier to understand.

šŸ’” Pro Tip: Functions are like recipes in baking - they provide a set of instructions to achieve a particular result.

Function Syntax šŸŽÆ

A Swift function is defined using the func keyword. The function name, parameters, and return type are specified within the function's definition.

swift
func functionName(parameters: types) -> returnType { // Function body }

Function Name

The function name should be descriptive and self-explanatory. It represents the purpose of the function.

šŸ“ Note: Function names should follow Swift's naming conventions: lowercase with words separated by camelCase.

Parameters

Parameters are the inputs a function accepts. They help the function perform different tasks based on the provided inputs.

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

In the above example, greet is a function that accepts one parameter, name, of type String.

Return Type

A function can return a value to the caller. The return type specifies the data type of the returned value.

swift
func calculateArea(width: Double, height: Double) -> Double { let area = width * height return area }

In this example, the calculateArea function accepts two parameters, width and height, and returns the area of a rectangle as a Double.

Calling Functions šŸŽÆ

To call a function, simply use its name followed by parentheses containing the required arguments.

swift
greet(name: "John") let result = calculateArea(width: 5.0, height: 10.0)

Function Examples šŸŽÆ

Example 1: Greeting Function

swift
func greet(name: String) { print("Hello, \(name)!") } greet(name: "John") // Output: Hello, John!

Example 2: Calculating Area Function

swift
func calculateArea(width: Double, height: Double) -> Double { let area = width * height return area } let rectangleArea = calculateArea(width: 5.0, height: 10.0) print("The area of the rectangle is: \(rectangleArea)") // Output: The area of the rectangle is: 50 ``
Quick Quiz
Question 1 of 1

What does a function do in Swift?

Quick Quiz
Question 1 of 1

What is the purpose of a function's name in Swift?

Quick Quiz
Question 1 of 1

What are parameters in a Swift function?

Quick Quiz
Question 1 of 1

What is the return type of a function in Swift?