将数字转换为相应单词的最佳方法是什么? [关闭]

问题描述 投票:-5回答:3
let numberDict = [ 1: "one", 2: "two", 3: "three", 4: "four", 5: "five"]
print(numberDict[5] ?? "don't know")

将数字转换为相应单词的最佳方法是什么?

swift
3个回答
4
投票

Foundation库有一个内置的NumberFormatter类,可以拼出数字:

let number = 1
let formatter = NumberFormatter()
formatter.numberStyle = .spellOut
let numberString = formatter.string(from: number)

在上面的例子中,numberString是“one”(可选)。请注意,NumberFormatter是区域设置感知的。


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

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";
© www.soinside.com 2019 - 2024. All rights reserved.