Today I created my second app - a simple body mass index calculator. The BMI is calculated by the following formula:
$$\dfrac{\text{weight}}{\text{(height)}^2}$$
The general meaning of the resulting BMI values:
- \$<18.5\$ = underweight
- \$18.5-25\$ = normal weight
- \$25-30\$ = overweight
- \$>30\$ = obese
My goal was to improve my skills and make something useful at the same time. I'm sharing my code in hope to get some constructive feedback. Is there anything I could improve?
My model file:
import Foundation
struct CalculatorBrain {
let weightInKG: Double
let heightInCM: Double
init(weightInKG: String, heightInCM: String) {
self.weightInKG = Double(weightInKG) ?? 0.0
self.heightInCM = Double(heightInCM) ?? 0.0
}
func calcBmi() -> Double {
return weightInKG / ((heightInCM / 100) * (heightInCM / 100))
}
}
The ViewController:
class ViewController: UIViewController {
@IBOutlet weak var weightTextField: UITextField!
@IBOutlet weak var heightTextField: UITextField!
@IBOutlet weak var resultTextField: UILabel!
@IBAction func calculateBtn(_ sender: Any) {
guard let weightInKG = weightTextField.text,
let heightInCM = heightTextField.text else {
return
}
let cm = CalculatorBrain(weightInKG: weightInKG, heightInCM: heightInCM)
let result = cm.calcBmi()
resultTextField.text = "BMI: \(result)"
}
}