-2

How do I convert this for block to swift 3

let row = textField.tag
if row >= arrayOfLinks.count {
   for var addRow = arrayOfLinks.count; addRow <= row; addRow += 1 {
       arrayOfLinks.append("")
   }
}

Thanks

Poseidon
  • 33
  • 3
  • 1
    http://stackoverflow.com/questions/36173379/warning-c-style-for-statement-is-deprecated-and-will-be-removed-in-a-future-ve/36173489#36173489 – Bhavin Bhadani Jan 03 '17 at 13:06

3 Answers3

2

A C-style for loop is not needed at all

let row = textField.tag
while arrayOfLinks.count <= row {
    arrayOfLinks.append("")
}
vadian
  • 274,689
  • 30
  • 353
  • 361
  • Note that the OPs original solution (intentional or not ...) appends a final element also when `arrayOfLinks.count` equals `row`, i.e., equivalent to using `<=` rather than `<` in the `while` loop termination condition above. – dfrib Jan 03 '17 at 14:38
0

Try this:

let row = textField.tag
if row >= arrayOfLinks.count {
   var addRow = arrayOfLinks.count
   while addRow <= row {
       arrayOfLinks.append("")
       addRow += 1
   }
}
MarmiK
  • 5,639
  • 6
  • 40
  • 49
Emil Laine
  • 41,598
  • 9
  • 101
  • 157
0

Since you repeatedly append the same (value) element, you needn't use a loop here, but can simply append a collection to the existing arrayOfLinks array:

if arrayOfLinks.count <= row {
    arrayOfLinks.append(contentsOf:
        [String](repeating: "", count: row - arrayOfLinks.count + 1))
}

This should also be more performant than repeatedly appending (same value) elements, not that this should be an issue, however.

Note also that (as per your original solution), a row value of e.g. 10 will yield a total (existing + new) of 11 elements in the numberOfEntries array.

dfrib
  • 70,367
  • 12
  • 127
  • 192