Logo
Swift Basics
Swift BasicsFunctions

Functions

Functions are reusable blocks of code that perform specific tasks within a program. They are a fundamental building block in Swift programming, allowing for code modularity and reusability. This section will guide you through defining and calling functions in Swift.

Defining Functions

Basic Function Syntax

In Swift, you define a function using the func keyword, followed by the function name, parameters, and the return type.

func greet(name: String) -> String {
    return "Hello, \(name)!"
}

Function with Multiple Parameters

Functions can have multiple parameters separated by commas.

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

Function with No Return Value

If a function doesn't return a value, you can omit the return type.

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

Calling Functions

To call a function, you use its name followed by the arguments in parentheses.

let message = greet(name: "John")
print(message)  // Output: Hello, John!

Default Parameter Values

You can provide default values for function parameters. If a value for that parameter is not provided when calling the function, the default value is used.

func display(name: String, age: Int = 30) {
    print("\(name) is \(age) years old.")
}

Variadic Parameters

A variadic parameter allows you to pass a varying number of arguments to a function.

func sum(numbers: Int...) -> Int {
    return numbers.reduce(0, +)
}

Conclusion

Functions in Swift are versatile and powerful, allowing for a wide range of use-cases. They help in making your code modular, reusable, and maintainable. Understanding how to define and call functions is essential for anyone learning Swift programming.

Book a conversation with us for personalize training today!

Was this helpful?
Logo