c++ - 检测到文本数字太大而无法快速转换为 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 编写一个等效的程序来检测相同的情况呢?
解决方案
在 Swift 中,我们使用初始化器来创建一个整数形式 a String
。nil
如果它不能从它创建一个初始化器,它就会返回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!")
}
推荐阅读
- c# - 允许静态文件同源.Net Core
- ios - 在其他屏幕中更新绑定后,SwiftUI 列表行未刷新
- ios - 在桌面视图上区分 iPhone 和 iPad
- oracle - 如何在 WHERE 条件下使用 PL/SQL 中的关联数组,使得关联数组的键值对是我表中的列名
- reactjs - 反应数组的计数值并计算总价
- typescript - 如何使用枚举作为类型
- sql - 有没有更简洁的方法从 EXEC sp_configure 获取值到变量中?
- python - 为什么我不能让 Selenium 使用 Python 3.8 和 Chrome 在我的 WhatsApp Web 中写消息?
- php - 在laravel中重定向到上一页
- java - ScrollView 不使用 onTouch 滚动