This is "homework" from a Swift course, which I'm currently taking. A mockup and the image-assets are provided by the instructor. We are supposed to create the layout and to write some appropriate code.
Here's the code of my ViewController:
import UIKit
class ViewController: UIViewController {
// MARK: Outlets
@IBOutlet weak var nameText: UITextField!
@IBOutlet weak var sizeText: UITextField!
@IBOutlet weak var weightText: UITextField!
@IBAction func clickHereButton(_ sender: UIButton) {
let name = nameText.text!
let size = Double(sizeText.text!)!
let weight = Double(weightText.text!)!
let bmi = weight / pow(size, 2)
let bmiRounded = (round(bmi * 10) / 10)
print(bmiRounded)
let uac = UIAlertController(title: "BMI for \(name)", message: "Your Body-Mass-Index is \(bmiRounded)", preferredStyle: .alert)
uac.addAction(UIAlertAction(title: "Okay", style: .default))
self.present(uac, animated: true, completion: nil)
}
}
What are your thoughts about my implementation? What would you have done differently and why?
Double(sizeText.text!)
andDouble(weightText.text!)
calls for trouble. Use optional binding instead. You could also set the keyboard type and define some valid ranges for the text fields. \$\endgroup\$UITextField
and displaying appropriate message if it isn't correct. For example on iPad user will be able to enter special symbols, even if you set decimal keyboard forUITextField
. Another thing that I would recommend - calculate BMI "live" when user type in value in text field \$\endgroup\$