首页 > 解决方案 > 检测到文本数字太大而无法快速转换为 Int

问题描述

我有一个用 C++ 编写的程序,我正在尝试创建另一个用 Swift 编写的具有相同功能的程序。C++ 代码可以做的一件事是,当给定的文本字符串包含的数值太大而无法转换为整数时,程序可以检测并报告该问题。因此,给定如下 C++ 代码:

#include <iostream>

int main() {
    try {
        auto value = std::stoi("999999999999999999999999999");
    }
    catch (const std::out_of_range&) {
        std::cerr << "The value is too large to convert to an integer.\n";
    }

    return 0;
}

有人怎么能用 Swift 编写一个等效的程序来检测相同的情况呢?

标签: c++swift

解决方案


在 Swift 中,我们使用初始化器来创建一个整数形式 a Stringnil如果它不能从它创建一个初始化器,它就会返回Int。因此,您可以选择将其绑定到一个新变量并查看它是否可以执行并相应地执行所需的工作:

let value = "999999999999999999999999999"

if let number = Int(value) {
    print(number)
} else {
    print("The value is too large to convert to an integer")
}

供参考

里面有Foundation一种叫做Decimal可以处理这个值和更多史诗数字的类型。

if let number = Decimal(string: text) {
    print(number)
} else {
    print("Probably it's not a number at all!")
}

您还可以检查文本是否仅包含十进制数字(使用 Foundation):

text.trimmingCharacters(in: .decimalDigits).isEmpty

所以合并在一起:

if let number = Int(text) {
    print(number)
} else if !text.trimmingCharacters(in: .decimalDigits).isEmpty {
    print("It's not a number!")
} else if let decimal = Decimal(string: text) {
    print("The value \(decimal) is too large to convert to an integer")
} else {
    assertionFailure("What else could be prevent us from creating an integer? That happened!")
}

推荐阅读