I've added decimal (floating point) functionality to my calculator implementation; it's working but I'm having trouble making it more concise and less ugly.
I'm trying to use the same method to handle both number keys and the decimal point, and whichever way I look at it, I either have to check for the button being pressed and then whether the user is just starting a new entry, or the other way around. I've even drawn a flowchart to see how could this be condensed with nested logical operators (||
, &&
) but couldn't get it to work.
Obviously I could write a separate method for the decimal key, but then I'd get to repeating the isTyping
verification there instead. Is there a simple way to do this or is code repetition inevitable at some point or another?
@IBAction func buttonDigit(sender: UIButton) {
let digit = sender.currentTitle!
if isTyping {
if digit == "." {
if !hasDecimal {
display.text = display.text! + digit
hasDecimal = true
}
} else {
display.text = display.text! + digit
}
} else {
if digit == "." {
display.text = "0" + digit
} else {
display.text = digit
}
isTyping = true
}
}