I'm trying to make an IOS Unit Converter app using swift. But I'm getting an exception when a textfield is empty after entering some value.
I've already tried to solve the problem with 'if let' and 'guard statement' but could not get it to work maybe I did something wrong somewhere.
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var textOunce: UITextField!
@IBOutlet weak var textPound: UITextField!
@IBOutlet weak var textGram: UITextField!
@IBOutlet weak var textStone: UITextField!
@IBOutlet weak var textStonePound: UITextField!
@IBOutlet weak var textKg: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
textOunce.delegate = self
textPound.delegate = self
textGram.delegate = self
textStone.delegate = self
textStonePound.delegate = self
textKg.delegate = self
textOunce.addTarget(self, action: #selector(self.textFieldDidChange(_:)), for: .editingChanged)
textPound.addTarget(self, action: #selector(self.textFieldDidChange(_:)), for: .editingChanged)
textGram.addTarget(self, action: #selector(self.textFieldDidChange(_:)), for: .editingChanged)
textStone.addTarget(self, action: #selector(self.textFieldDidChange(_:)), for: .editingChanged)
textStonePound.addTarget(self, action: #selector(self.textFieldDidChange(_:)), for: .editingChanged)
textKg.addTarget(self, action: #selector(self.textFieldDidChange(_:)), for: .editingChanged)
}
@objc func textFieldDidChange(_ textField: UITextField) {
var toOunce = Double(textOunce.text!)!
toOunce = toOunce / 16
textPound.text = "\(toOunce)"
}
}
I want to dynamically fill the other textfields when the user enters a value on a textfield and set the value to zero instead of throwing a nil exception if the user decides to erase all the values they entered in a textfield.