import Foundation
func percentageChange(oldValue: Double, newValue: Double) throws -> Double {
guard oldValue != 0 else {
throw NSError(domain: "PercentageError", code: 1,
userInfo: [NSLocalizedDescriptionKey: "oldValue cannot be zero"])
}
return ((newValue - oldValue) / oldValue) * 100.0
}
let oldValue = 45.0
let newValue = 57.0
do {
let change = try percentageChange(oldValue: oldValue, newValue: newValue)
print(String(format: "Percentage change: %.2f%%", change))
} catch {
print("Error:", error.localizedDescription)
}
/*
run:
Percentage change: 26.67%
*/