0

Why does this code count 6 elements, as 9 ("wrong") in swift playground.

var stringArray = ["1", "2", "3", "4", "5", "6"]

for var i = 0; i < 3; i++ {
    stringArray.append("Paragraph" + "\(i)")
}


func concat (array: [String]) -> String {
    let count = UInt32(stringArray.count)                      ** --> =9 **
    let randomNumberOne = Int(arc4random_uniform(count))
    let randomNumberTwo = Int(arc4random_uniform(count))
    let randomNumberThree = Int(arc4random_uniform(count))

    let concatString = array[randomNumberOne] + array[randomNumberTwo] + array[randomNumberThree]

    return concatString
}

let finalString = concat(stringArray)

...but count this code as 6 (correct)

var stringArray = ["1", "2", "3", "4", "5", "6"]              ** --> =6 **

let count = UInt32(stringArray.count)

Does it have something to do with 64 vs 32 bit? I have Xcode Version 6.0 (6A313).

KML
  • 2,302
  • 5
  • 26
  • 47
  • You are appending new elements to the same stringArray which already has content ["1", "2", "3", "4", "5", "6"]. Then you append the "paragraph \(i)" string to it 3 times. So, the new content is now, ["1", "2", "3", "4", "5", "6", "Paragraph 1", "Paragraph 2", "Paragraph 3"]. Thats how the count reached to 9. – Sandeep Sep 20 '14 at 11:56
  • 1
    @insane-36 you should post your comment as an answer. – rob mayoff Sep 20 '14 at 13:34

1 Answers1

0

You are appending new elements to the same stringArray which already has content ["1", "2", "3", "4", "5", "6"]. Then you append the "paragraph (i)" string to it 3 times. So, the new content is now, ["1", "2", "3", "4", "5", "6", "Paragraph 1", "Paragraph 2", "Paragraph 3"]. Thats how the count reached to 9.

Sandeep
  • 20,908
  • 7
  • 66
  • 106