Futhark Futhark - 1 year ago 88
Swift Question

Show an Array of 10 Ints in a label

I'm trying to build a basic multiplication app that will show your 1 times tables up to 10 times tables depending which number you type into the text field.

When i run my code my label only produces 1 line which is the result of the last multiplication calculated for example 10 times 8 is 80, the other 9 do not get added, also after this my full array displays showing the correct answer to the tables. here is my code

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var numberTextField: UITextField!

@IBOutlet weak var tablesLabel: UILabel!

var tablesArray = [Int]()

var number = 0

override func viewDidLoad() {
// Do any additional setup after loading the view, typically from a nib.

@IBAction func tablesButtonTapped(_ sender: AnyObject) {

if numberTextField.text == "" {
print("Sorry you must enter a number between 1 and 10")
} else {
tablesArray = []
tablesLabel.text = ""
multiplyBy(number: Int(numberTextField.text!)!)
numberTextField.text = ""
func multiplyBy(number: Int) {

for index in 1...10 {
tablesArray.append(index * number)
tablesLabel.text = ("\(index) times \(number) is \(tablesArray)")
tablesLabel.isHidden = false

Any help is much appreciated.

Answer Source


tablesLabel.text = ("\(index) times \(number) is \(tablesArray)")


tablesLabel.text = ("\(tablesLabel.text ?? "") \(index) times \(number) is \(tablesArray)")

You overwrite the label's text every time. This does not overwrite the label's text and adds the new text to it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download