How to Add two Numbers in Swift Program?


This tutorial will discuss how to write a swift program to add two numbers.

Adding two numbers in Swift language is simple and can be performed with the help of the addition arithmetic operator(+). The arithmetic addition operator (+) uses two numbers as operands and returns their sum as output.

In this operator, both the operands should be of the same data types, For example swift allows adding a float into float without an issue but if we will try to add different types of data types using (+) operator then the compiler will raise an error, For example adding an Int and Float will raise a compile time error.

Syntax

Following is the syntax of Swift arithmetic addition operator (+) −

operand1 + operand2

Algorithm to add two numbers

  • Step 1 − Define two variables

  • Step 2 − Enter the value of those variables

  • Step 3 − Perform addition of those two variables

  • Step 4 − Print the output

Example

The following Swift program will show how to calculate the sum of two numbers.

import Foundation
import Glibc

var num1 = 190
var num2 = 243

var num3 = 40.3
var num4 = 34.56

var sum1 = num1 + num2
var sum2 = num3 + num4

print("Expression: 190 + 243, Result:", sum1)
print("Expression: 40.3 + 34.56, Result:", sum2)

Output

Expression: 190 + 243, Result: 433
Expression: 40.3 + 34.56, Result: 74.86

Example

Now we will check what will happen when we try to add two numbers of a different data types with the help of the below example. Here the num1 is of integer type and num2 is of float type.

import Foundation
import Glibc
var num1 = 20
var num2 = 40.45
var sum = num1 + num2

print("Expression: 190 + 243, Result:", sum)

Output

main.swift:8:16: error: binary operator '+' cannot be applied to operands of type 'Int' and 'Double'
var sum = num1 + num2
~~~~ ^ ~~~~
main.swift:8:16: note: overloads for '+' exist with these partially matching parameter lists: (Date, TimeInterval), (DispatchTime, Double), (DispatchWallTime, Double), (Double, Double), (Int, Int)
var sum = num1 + num2

In the above code, we are getting an error because we are trying to add two different data types that are Int and Double, and the (+)operator does not support the addition of different data types.

Updated on: 29-Jul-2022

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements