Doughnut Man Doughnut Man - 1 year ago 56
Swift Question

Adding and Displaying Integers in a Label

I'm making a scoring app where you can keep track of the score for different board games or such that you are playing. Here is the code I have so far.

override func viewDidLoad() {

@IBOutlet weak var scoreTextField: UITextField!
@IBOutlet weak var scoreTotal: UILabel!

@IBAction func buttonPressed(sender: AnyObject) {

if let number = Int(scoreTextField.text!){
scoreTotal.text = "\(number)"


I want to be able to type in the textfield and when the button is pressed it add both the previous number and the one in the textfield together and display the result in the label. Can anyone help me please? Thank you!

Answer Source
if let number = Int(scoreTextField.text!){
    let previousScoreText = scoreTotal.text
    if previousScoreText == nil || previousScoreText.isEmpty == true {
        previousScoreText = "0"
    scoreTotal.text = "\(Int(previousScoreText!)! + number)"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download