swift - 在使用字典时映射列表?

标签 swift function dictionary

我似乎无法理解它是如何产生 ["OneSix", "FiveEight", "FiveOneZero"] 的。我看到它的方式是它通过列表进行映射,并且 % 符号首先将数字评估为“六”。那么,为什么结果中“一”排在“六”之前?

这部分让我感到困惑:

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"]

最佳答案

了解循环如何工作的最好方法是用铅笔和纸一次一步地完成它。

假设数字是 123。然后循环将像这样工作:

var output = ""
while number > 0 {
    output = digitNames[number % 10]! + output
    number /= 10
}
  • 在初始迭代 output=""number=123
  • 之前
  • 在第一次迭代之后,输出变成了"Three"并且number变成了12`
  • 第二次迭代后,输出变为"TwoThree",数字变为1
  • 在最后一次迭代后 output 变为 "OneTwoThree" 并且 number 变为 0

换句话说,output 从后往前增长,但同时 number 也从后往前“收缩”,所以正确的在整个过程中保持秩序。

关于swift - 在使用字典时映射列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36240731/

相关文章:

ios - iOS 发生冲突后,如何移动多个 View ?

javascript - JS : Assignment within if statment doesn't work

c++ - 比较器函数 vector 的默认参数

c - C 结构中函数的参数

python - 字典键中的通配符

时间:2019-03-08 标签:c++STLmap::find()

swift - 了解闭包语法

ios - 我的应用程序因异常 EXC_BREAKPOINT (SIGTRAP) 而被拒绝

swift - 自定义 UITableViewCell 中的 UIView 在滚动时重绘

c++ - 将抽象类对象从映射存储到抽象类引用