swift

AddTwoNumbers()

Parameters:

Returns:

This function accepts two numbers as input and returns their sum. It is a basic function which is commonly used in many programs.

Addition
Variables
Return Statements
Easy dificulty

Hello there, dear programmer! We welcome you to this blog post. We know coding is no small feat, and we appreciate your efforts. In the context below, we will be walking you through the steps to write a function in Swift that adds two numbers. This guide is direct, simple and jargon-free. Let's dive into the world of programming and explore the wonders that can be achieved with a few lines of code. Happy Learning!

Step 1: Declare The Function

First, begin by declaring the function. In Swift, functions are defined using the func keyword. Our function will be called addTwoNumbers and it will accept two arguments - both of which are integers.

func addTwoNumbers(num1: Int, num2: Int) {

}

Step 2: Add The Function Logic

Now, inside this function, we will write the logic to add the two received numbers. For doing this, simply use the + operator.

func addTwoNumbers(num1: Int, num2: Int) {
  let sum = num1 + num2
}

Step 3: Return The Sum

By the time, we have calculated the sum. But, we also need to return this sum from the function. As per Swift's syntax, use the return keyword.

func addTwoNumbers(num1: Int, num2: Int) -> Int {
  let sum = num1 + num2
  return sum
}

Step 4: Call The Function

Finally, let's call this function with some numbers.

let result = addTwoNumbers(num1: 5, num2: 7)

Step 5: Print The Result

To verify if our code is working properly, print the result on the console.

print(result)

Conclusion:

The final implementation of the function addTwoNumbers is:

func addTwoNumbers(num1: Int, num2: Int) -> Int {
  let sum = num1 + num2
  return sum
}

let result = addTwoNumbers(num1: 5, num2: 7)
print(result)

This program will print 12, which is the sum of 5 and 7.

Learn function in:

Mathematical principle

The principle here is the basic operation of addition. In mathematics, addition combines two or more numbers into a single number known as the sum. In swift, the `+` operator is used to perform this operation.

Learn more