使用字典时映射列表?

时间:2016-03-26 20:50:59

标签: swift function dictionary

我似乎无法理解它是如何产生[" 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"]

1 个答案:

答案 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从后到前“缩小”,所以通过这个过程保持正确的顺序

相关问题