Read each field with a NumberFormatter set to the user's region, so "1,5" works in Indonesia and "1.5" in the US. Calculate with Decimal, check for zero before dividing, and show a message instead of crashing when a field is empty or not a number. The 2018 version force-unwrapped Int(...)!, which stopped the app on an empty field and on division by zero, and dropped every fraction.
SWIFT TIPS · UIKIT · FOUNDATION
First posted on July 8, 2018 for Swift 4, as "Simple Calculator UItextField Two Input Swift 4". Rewritten on November 17, 2026. The calculation code was run on a Mac with Swift 6.2.3 (Xcode 26.2) on macOS 26.0.1. The view controller was type-checked against the iOS 26.2 SDK in Swift 5 and Swift 6 modes with iOS 15 as the deployment target, but not run on a device.
The 2018 post was a small calculator: two text fields, a result label, and four buttons for plus, minus, times and divide. Each button converted both fields with Int(label1.text!)! and showed the result. It's a nice first UIKit exercise, and it's also a compact lesson in everything that can go wrong with user input.
What the 2018 code did with bad input
I ran the same expressions on a Mac with two inputs a user could easily type:
"10" / "0": Fatal error: Division by zero
"" + "3": Fatal error: Unexpectedly found nil while unwrapping an Optional value
Both stop the program. An empty field makes Int("") return nil, and the ! turns that into a crash. Dividing an Int by zero is also a crash in Swift, not infinity. And even with valid input, Int math drops fractions: in the test below, 7 divided by 2 as Int printed 3.
Parsing and calculating safely
import Foundation
enum CalcError: Error, CustomStringConvertible {
case notANumber(String), divisionByZero
var description: String {
switch self {
case .notANumber(let s): return "not a number: \(s.debugDescription)"
case .divisionByZero: return "can't divide by zero"
}
}
}
/// Reads a number the way the user's region writes it ("1,5" in Indonesia, "1.5" in the US).
func parseNumber(_ text: String, locale: Locale) throws -> Decimal {
let trimmed = text.trimmingCharacters(in: .whitespaces)
let formatter = NumberFormatter()
formatter.locale = locale
formatter.numberStyle = .decimal
formatter.generatesDecimalNumbers = true
guard !trimmed.isEmpty, let n = formatter.number(from: trimmed) as? NSDecimalNumber else {
throw CalcError.notANumber(text)
}
return n.decimalValue
}
enum Operation { case add, subtract, multiply, divide }
func calculate(_ a: Decimal, _ op: Operation, _ b: Decimal) throws -> Decimal {
switch op {
case .add: return a + b
case .subtract: return a - b
case .multiply: return a * b
case .divide:
guard b != 0 else { throw CalcError.divisionByZero }
return a / b
}
}
func show(_ d: Decimal, locale: Locale) -> String {
d.formatted(.number.precision(.fractionLength(0...6)).locale(locale))
}
let id = Locale(identifier: "id_ID"), us = Locale(identifier: "en_US")
let cases: [(String, Operation, String, Locale)] = [
("7", .divide, "2", id), ("1,5", .multiply, "4", id), ("1.5", .multiply, "4", us),
("1.000", .add, "1", id), ("10", .divide, "0", id), ("", .add, "3", id), ("abc", .add, "3", id),
("0,1", .add, "0,2", id),
]
for (a, op, b, loc) in cases {
do {
let r = try calculate(try parseNumber(a, locale: loc), op, try parseNumber(b, locale: loc))
print("\(a.debugDescription) \(op) \(b.debugDescription) [\(loc.identifier)] = \(show(r, locale: loc))")
} catch {
print("\(a.debugDescription) \(op) \(b.debugDescription) [\(loc.identifier)] -> error: \(error)")
}
}
print("Int 7 / 2 =", 7 / 2, "| Double(\"1,5\") =", Double("1,5") as Any)
Output:
"7" divide "2" [id_ID] = 3,5
"1,5" multiply "4" [id_ID] = 6
"1.5" multiply "4" [en_US] = 6
"1.000" add "1" [id_ID] = 1.001
"10" divide "0" [id_ID] -> error: can't divide by zero
"" add "3" [id_ID] -> error: not a number: ""
"abc" add "3" [id_ID] -> error: not a number: "abc"
"0,1" add "0,2" [id_ID] = 0,3
Int 7 / 2 = 3 | Double("1,5") = nil
Reading the results:
- Fractions survive. 7 divided by 2 is 3,5 with an Indonesian locale.
- The region's separators work. "1,5" times 4 is 6 for Indonesia, and "1.5" times 4 is 6 for the US.
Double("1,5")on the last line returnsnil, because the plain initializer only understands a dot. Anyone in a region that writes decimals with a comma will type one, so the number formatter matters. - Grouping separators too. "1.000" in Indonesian means one thousand, so adding 1 gives 1.001. A parser that ignores the locale would read it as one.
- Errors are messages. Dividing by zero, an empty field and "abc" each produce an error the screen can show.
- Decimal keeps money right. 0,1 plus 0,2 is exactly 0,3.
The view controller
import UIKit
final class CalculatorViewController: UIViewController {
@IBOutlet private weak var firstField: UITextField!
@IBOutlet private weak var secondField: UITextField!
@IBOutlet private weak var resultLabel: UILabel!
private enum Operation { case add, subtract, multiply, divide }
override func viewDidLoad() {
super.viewDidLoad()
firstField.keyboardType = .decimalPad
secondField.keyboardType = .decimalPad
}
@IBAction func plusTapped(_ sender: UIButton) { run(.add) }
@IBAction func minusTapped(_ sender: UIButton) { run(.subtract) }
@IBAction func timesTapped(_ sender: UIButton) { run(.multiply) }
@IBAction func divideTapped(_ sender: UIButton) { run(.divide) }
private func run(_ op: Operation) {
guard let a = number(firstField.text), let b = number(secondField.text) else {
resultLabel.text = "Enter two numbers"
return
}
let result: Decimal
switch op {
case .add: result = a + b
case .subtract: result = a - b
case .multiply: result = a * b
case .divide:
guard b != 0 else { resultLabel.text = "Can't divide by zero"; return }
result = a / b
}
resultLabel.text = result.formatted(.number.precision(.fractionLength(0...6)))
}
/// Reads "1,5" or "1.5" depending on the user's region, as the decimal pad types it.
private func number(_ text: String?) -> Decimal? {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.generatesDecimalNumbers = true
guard let text, !text.isEmpty else { return nil }
return (formatter.number(from: text) as? NSDecimalNumber)?.decimalValue
}
}
The four buttons share one run(_:) method instead of repeating the conversion four times. The fields use .decimalPad, a keyboard with numbers and a decimal separator. The number(_:) function reads the text with the user's current locale. The result is formatted with up to six decimals, so 10 divided by 3 shows a readable 3,333333 instead of a long run of digits.
A quick check for your project
- Search for
Int(andDouble(followed by.text!)!. Each one crashes on an empty field. - Search for
/on values that come from the user, and check for zero first. - Set your device region to Indonesia and type a decimal number into every numeric field in your app.
What the 2018 version said
Each of the four actions was one line, for example self.sum.text = String(Int(label1.text!)! * Int(label2.text!)!), and the plus action also showed the same sum written in three steps. The text fields were named label1 and label2 in the code, which is worth renaming too.
Keep reading on JR Devhub
Comments
Best online swift course
Ranorex Online Training