Swift – Implementing a basic calculator
In this tutorial, we will learn how to implement a basic calculator in Swift that performs addition, subtraction, multiplication, and division. We will handle user inputs and display the results for each operation.
Understanding the Problem
A basic calculator performs operations such as addition, subtraction, multiplication, and division on two numbers. In this implementation, we will:
- Take two numbers as inputs.
- Allow the user to choose an operation.
- Perform the selected operation and display the result.
- Handle edge cases, such as division by zero.
Swift Program for a Basic Calculator
Here’s the implementation:
import Foundation
// Function to perform calculator operations
func calculate(_ num1: Double, _ num2: Double, operation: String) -> Double? {
switch operation {
case "+":
return num1 + num2
case "-":
return num1 - num2
case "*":
return num1 * num2
case "/":
if num2 != 0 {
return num1 / num2
} else {
print("Error: Division by zero is not allowed.")
return nil
}
default:
print("Invalid operation. Please choose +, -, *, or /.")
return nil
}
}
// Example usage
let num1 = 10.0
let num2 = 5.0
if let result = calculate(num1, num2, operation: "+") {
print("\(num1) + \(num2) = \(result)")
}
if let result = calculate(num1, num2, operation: "-") {
print("\(num1) - \(num2) = \(result)")
}
if let result = calculate(num1, num2, operation: "*") {
print("\(num1) * \(num2) = \(result)")
}
if let result = calculate(num1, num2, operation: "/") {
print("\(num1) / \(num2) = \(result)")
}
Explanation:
calculate(_:_:operation:)
: A function that takes two numbers and an operation (+, -, *, /) as inputs and performs the corresponding calculation.switch operation
: Determines which operation to perform based on the input operator.- Handles division by zero by checking if
num2
is zero before performing the division. - Returns
nil
for invalid operations or division by zero.
Handling User Input
To make the program interactive, you can use readLine()
to take inputs from the user:
print("Enter the first number:")
if let input1 = readLine(), let num1 = Double(input1) {
print("Enter the second number:")
if let input2 = readLine(), let num2 = Double(input2) {
print("Choose an operation (+, -, *, /):")
if let operation = readLine() {
if let result = calculate(num1, num2, operation: operation) {
print("Result: \(result)")
}
} else {
print("Invalid operation.")
}
} else {
print("Invalid input for the second number.")
}
} else {
print("Invalid input for the first number.")
}
Complete Swift Program
Here’s the complete program, combining static examples and interactive user inputs:
import Foundation
// Function to perform calculator operations
func calculate(_ num1: Double, _ num2: Double, operation: String) -> Double? {
switch operation {
case "+":
return num1 + num2
case "-":
return num1 - num2
case "*":
return num1 * num2
case "/":
if num2 != 0 {
return num1 / num2
} else {
print("Error: Division by zero is not allowed.")
return nil
}
default:
print("Invalid operation. Please choose +, -, *, or /.")
return nil
}
}
// Interactive Calculator
print("Enter the first number:")
if let input1 = readLine(), let num1 = Double(input1) {
print("Enter the second number:")
if let input2 = readLine(), let num2 = Double(input2) {
print("Choose an operation (+, -, *, /):")
if let operation = readLine() {
if let result = calculate(num1, num2, operation: operation) {
print("Result: \(result)")
}
} else {
print("Invalid operation.")
}
} else {
print("Invalid input for the second number.")
}
} else {
print("Invalid input for the first number.")
}
// Static Examples
let example1 = calculate(12, 4, operation: "+") // Addition
print("12 + 4 = \(example1 ?? 0)")
let example2 = calculate(12, 4, operation: "/") // Division
print("12 / 4 = \(example2 ?? 0)")
let example3 = calculate(12, 0, operation: "/") // Division by zero
print("12 / 0 = \(example3 ?? 0)")
Output:
Enter the first number:
10
Enter the second number:
20
Choose an operation (+, -, *, /):
+
Result: 30.0
12 + 4 = 16.0
12 / 4 = 3.0
Error: Division by zero is not allowed.
12 / 0 = 0.0
Program ended with exit code: 0
This program can handle user inputs dynamically while also providing static examples to test different operations. It includes error handling for invalid inputs and division by zero.