Swift – Function with Parameters

To define a function that can accept arguments, specify the parameters with respective types in the parenthesis of function definition.

The syntax to define a function with parameters is

func functionName(parameter1: <T>, parameter2: <T>) {
    //body
}

Example

In the following example, we define a function add that accepts two Int values and print their sum.

main.swift

func add(a: Int, b: Int) {
    let result = a + b
    print("The result is \(result)")
}

add(a: 4, b: 3)

Output

ADVERTISEMENT

Conclusion

In this Swift Tutorial, we learned how to define a function with parameters in Swift programming.