Search code examples
swiftcountswift-playgrounduint32

Why does UInt32(stringArray.count) count wrong in a function but correct alone in swift playground?


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).


Solution

  • 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.