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

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-12 04:58:21

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/25948339/why-does-uint32stringarray-count-count-wrong-in-a-function-but-correct-alone-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!