OneBite.Dev - Coding blog in a bite size

Add Two Numbers In Swift

Code snippet for how to Add Two Numbers In Swift with sample and detail explanation

Swift is a powerful and interactive programming language developed by Apple for iOS, macOS, watchOS, and tvOS app development. This article will teach you how to write simple Swift code that adds two numbers.

Code snippet: Adding Two Numbers

The Swift language is quite simple and concise. Here is a brief code snippet that demonstrates how to add two numbers:

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

let result = addTwoNumbers(num1: 3, num2: 5)
print(result)  // Outputs: 8

Code Explanation for Adding Two Numbers

The code snippet provided performs a very simple task: adding together two integers. Here’s how it works, step by step.

  1. We first define a function addTwoNumbers(num1: Int, num2: Int) -> Int. This is a function that takes in two parameters, num1 and num2, both of which should be Int (integer) type. The -> Int after the parentheses indicates that this function will return an integer.

  2. Inside the function, we see the line return num1 + num2. This instruction tells Swift to add together num1 and num2 and then send back, or “return”, the result.

  3. Outside the function, we create a variable let result = addTwoNumbers(num1: 3, num2: 5). This line calls the function addTwoNumbers, giving it the numbers 3 and 5 as arguments to add together. The result of this operation (in this case, 8) is then stored in the result variable.

  4. Finally, print(result) is used to print the result of our addition to the console. In this example, it will print 8.

And that’s it! You’ve successfully written a function in Swift to add two numbers together. Feel free to change the values of num1 and num2 to add together different numbers.

swift