Swift: How to (easily) Calculate two numbers
Doing calculations and showing the answer in Swift is really easy.
Thank you for reading this post, don't forget to subscribe!
This example will do just that and print the answer to the terminal. But you could change the code to show the problems and the answer in a UILabel.
Here’s the code:
import UIKit
import Foundation
let firstNumber = 56
let secondNumber = 23
let answer = (firstNumber + secondNumber)
print (firstNumber, “+”, secondNumber, “=”, answer)
As always, import UIKit and then the Foundation Frameworks so the code will work correctly.
1. Assign two variables two different numbers to give the computer something to calculate.
2. Assign a variable to show the answer to the calculations.
3. Show the problem and the answer to the terminal – 56 + 23 = 79.
4. That’s it.
Note: The ( ) around the firstNumber and lastNumber means that the computer will always calculate the variables in-between the ( ) first, so you can preform any other calculations after that.
Like so:
let answer = (firstNumber + secondNumber) / 30