let numberDict = [ 1: "one", 2: "two", 3: "three", 4: "four", 5: "five"]
print(numberDict[5] ?? "don't know")
将数字转换为相应字词的最佳方法是什么?
答案 0 :(得分:4)
Foundation库有一个内置的NumberFormatter
类,可以拼出数字:
let number = 1
let formatter = NumberFormatter()
formatter.numberStyle = .spellOut
let numberString = formatter.string(from: number)
在上面的例子中,numberString
是"一个" (可选的)。请注意,NumberFormatter
不能识别区域设置。
答案 1 :(得分:1)
如果你想发疯,你可以使用枚举(但在某种程度上,它会回到switch
):
enum Number: Int, CustomStringConvertible {
case one = 1
case two = 2
case three = 3
case four = 4
case five = 5
var description: String {
switch self {
case .one: return "one"
case .two: return "two"
case .three: return "three"
case .four: return "four"
case .five: return "five"
}
}
}
let number = 3
let enumedNumber: Number? = Number(rawValue: number)
print(enumedNumber ?? "Don't know")
答案 2 :(得分:0)
如果您需要自己定义名称,最短的解决方案是
let array = ["one", "two", "three", "four", "five"]
let number = 1
print(number > 0 && number <= array.count ? array[number - 1] : "unknown")
如果你喜欢疯狂的方法,你可以使用
print(NSLocalizedString(number, comment: ""))
包含
的Localizable.strings
文件
"1" = "one";
"2" = "two";
"3" = "three";
"4" = "four";
"5" = "five";