我似乎无法理解它是如何产生[" OneSix "," FiveEight", " FiveOneZero&#34]。我看到它的方式是它通过列表进行映射,%符号将数字评估为" Six"第一。那么为什么" One"来之前"六"在结果?
这部分让我困惑:
output = digitNames[number % 10]! + output number /= 10
let digitNames = [
0: "Zero", 1: "One", 2: "Two", 3: "Three", 4: "Four",
5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine"
]
let numbers = [16, 58, 510]
let strings = numbers.map {
(number) -> String in
var number = number
var output = ""
while number > 0 {
output = digitNames[number % 10]! + output
number /= 10
}
return output
}
// strings is inferred to be of type [String]
// its value is ["OneSix", "FiveEight", "FiveOneZero"]
答案 0 :(得分:1)
查看循环如何工作的最佳方法是使用铅笔和纸张一步一步地完成。
我们说这个数字是123
。然后循环就像这样:
var output = ""
while number > 0 {
output = digitNames[number % 10]! + output
number /= 10
}
output=""
和number=123
output
变为"Three"
和number becomes
12` output
变为"TwoThree"
且数字变为1
output
变为"OneTwoThree"
且数字变为0
换句话说,output
从后到前都在增长,但同时number
从后到前“缩小”,所以通过这个过程保持正确的顺序