0
0
Swiftprogramming~5 mins

Function declaration syntax in Swift

Choose your learning style9 modes available
Introduction
Functions help you organize your code into small, reusable pieces that do one job.
When you want to repeat a task many times without writing the same code again.
When you want to break a big problem into smaller, easier steps.
When you want to give a name to a set of instructions to make your code clearer.
When you want to use the same code in different parts of your app.
When you want to test parts of your code separately.
Syntax
Swift
func functionName(parameters) -> ReturnType {
    // code to run
}
The keyword func starts the function declaration.
Parameters are optional; if there are none, use empty parentheses ().
Examples
A simple function with no parameters and no return value.
Swift
func greet() {
    print("Hello!")
}
A function that takes two numbers and returns their sum.
Swift
func add(a: Int, b: Int) -> Int {
    return a + b
}
A function with one parameter that prints a greeting.
Swift
func sayHello(to name: String) {
    print("Hello, \(name)!")
}
Sample Program
This program defines a function to multiply two numbers and then prints the result.
Swift
func multiply(x: Int, y: Int) -> Int {
    return x * y
}

let result = multiply(x: 4, y: 5)
print("4 times 5 is \(result)")
OutputSuccess
Important Notes
Functions can have zero or more parameters.
If a function returns a value, use the arrow -> followed by the return type.
Use return to send back a value from the function.
Summary
Functions start with the keyword func.
They can take inputs called parameters and can return a value.
Functions help keep code organized and reusable.