OneBite.Dev - Coding blog in a bite size

Call A Function With Parameter In Swift

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

Swift, as a modern programming language designed by Apple, allows developers to write function calls with parameters quite effortlessly. This article will illustrate both how to call a function with parameters in Swift and provide a detailed explanation of the whole process.

Code Snippet: Calling a Function with Parameters in Swift

Below is a simple Swift function greet which takes two parameters - name and age:

func greet(name: String, age: Int) {
    print("Hello, \(name). You are \(age) years old.")
}

greet(name: "Taylor Swift", age: 31)

You can use this function to greet anyone by passing their name and age as the argument.

Code Explanation: Calling a Function with Parameters in Swift

Firstly, you need to define a function. Use the func keyword to initiate a function declaration in Swift. After func, write the name of the function which in our case is greet. Immediately after the function name, define your parameters inside the parenthesis. The syntax is simple: the name of the parameter followed by a colon and its type. In our function, we have two parameters: name and age. name is of type String and age is of type Int.

After defining the parameters, use the curly brackets {} to open and close the function body. Inside these curly brackets, specify what the function should do. Our greet function is supposed to print a greeting to the console hence we’ve used the print function. Inside the print function we concatenate a string and the parameters using a backslash \.

To call or use the defined function, simply type its name followed by parenthesis (). Inside the parenthesis, pass in the real values as arguments that correspond with the parameters. In our example, we’ve called the greet function with "Taylor Swift" and 31 as arguments.

Run your code. If everything is done correctly, your console will print “Hello, Taylor Swift. You are 31 years old.”

By following these steps, you should be able to create and call any function with parameters in Swift.

swift