OneBite.Dev - Coding blog in a bite size

Declare A Function With Multiple Parameter In Swift

Code snippet for how to Declare A Function With Multiple Parameter In Swift with sample and detail explanation

Swift, the powerful and intuitive programming language for iOS, macOS, watchOS, and tvOS, offers developers the flexibility of defining functions with multiple parameters. This simple article will walk you through how you can declare a function with multiple parameters in Swift.

Code snippet: Declaring a Function with Multiple Parameters

Here’s a simple example of how you can define a function with multiple parameters in Swift:

func greet(person: String, day: String) -> String {
    return "Hello \(person), today is \(day)."
}
let message = greet(person: "Bob", day: "Tuesday")
print(message)

Code Explanation: Declaring a Function with Multiple Parameters

In this code example, we’ve declared a function named greet() which accepts two parameters: person and day.

The first line of the code block declares the function. Here, func is a keyword followed by the name of the function greet(). Inside the parentheses, we have our function parameters person of type String and day also of type String. The -> String part signifies the return type of the function that is also String.

The function body inside the curly braces {} consists of the actual code to be executed when the function is called. It contains a single statement that returns a string composed of the literal “Hello”, the person argument, the string “today is”, and the day argument.

On the third line, we then call the function while passing the appropriate parameters and assign the return value to the constant variable message.

Finally, the last line of the code prints out the return value.

The output will be: “Hello Bob, today is Tuesday.”

That’s it! As you can see, declaring functions with multiple parameters in Swift not only makes your code more readable and flexible but also allows for code reusability.

swift