Chris Chris - 1 year ago 45
iOS Question

Putting array into label in swift

@IBAction func generateBtn(sender: UIButton) {
let strt = UInt32(strtNum.text!)
let end = UInt32(endNum.text!)
let ttlNums = Int(amtNums.text!)

let x = RandomNum()

var z = 0

while z<ttlNums{
let y = x.rndNumGen(strt!, end: end!)
z += 1
var h = [String]()
let display:String = h.joinWithSeparator(", ")

winningNums.text = display
print (display)


I don't know what is wrong with this code. I am trying to put the string display into the label and it prints out the last number from the random number generator. When i print it to the console it shows all of the random numbers.

Answer Source

The primary issue here is that your array is created fresh in every loop iteration, and your label is being set in every loop iteration. That means that the array will only ever contain the element made in that iteration, after which it's reset to a new array, and a new element is added. The array needs to be initialized once at the start, and have elements added to it repeatedly in the loop, then put into the label once at the end.

@IBAction func generateBtn(sender: UIButton) {
    guard let startText = strtNum.text, let start = UInt32(startText),
          let endText = endNum.text, let end = UInt32(endText),
          let ttlText = amtNums.text, let ttlNums = UInt32(ttlText) else {
              //one of these is nil, handle it gracefully here

    let randomGenerator = RandomNum()

    var h = [String]()
    for _ in 0..<ttlNums {
        let randomNum = randomGenerator.rndNumGen(start, end: end)

    let display = h.joinWithSeparator(", ")

    winningNums.text = display

I've made a few other changes to bring this code in line with Swift best practices and conventions:

  1. Don't force unwrap. Use an if let or guard let binding to safely handle nil values.
  2. Give your variables meaningful names. Avoid single-letter names except in specific instances.
  3. Don't put spaces beside a function/method name and the proceeding brackets.
  4. Don't use a while loop to iterate over a known range. Instead, use a for in loop.
  5. Dn't type in t3xtspk, it mks ur code look lik an angsty teenagr wrote it. Autocomplete will finish off words for you, so you barely end up typing anyway. Make it easy and readable.

I would suggest you make a few changes yourself:

  1. Rename generateBtn. Functions/methods DO things, they're actions. They should be named with verbs, or verb phrases. Perhaps try something like displayRandomArray.
  2. Refactor the random array generation into its own method.
  3. Rename RandomNum. By the looks of it, it's not a number at all, it's a random number generator. Perhaps try RandomNumberGenerator
  4. Rename h.
  5. Add code to deal with what happens when the .text is nil, or what happens when it contains a string that isn't a UInt32 (thus causing the UInt32 initializer to fail and return nil)