objective-c - 检查数组值是否是 Swift 4 中的有效数字
问题描述
我有以下在 Objective-C 中工作的代码:
NSScanner *scanner ;
for(int i = 0; i < [expression count]; i = i + 2)
{
scanner = [NSScanner scannerWithString:[expression objectAtIndex:i]];
BOOL isNumeric = [scanner scanInteger:NULL] && [scanner isAtEnd];
if(!isNumeric)
return false;
}
return true;
我需要 Swift 4 中的等效代码。我尝试了不同的方法,但无法解决。要求是检查数组的元素是否为数字。
解决方案
要检查一个对象是否是一个数字(Int
在你的情况下),你可以做两件事:
is
通过或类型检查as?
这仅检查类型而不检查内容
let isNumberType = "1" is Int print(isNumberType) //false because "1" is of type String
Int
通过它的初始化程序创建一个这会返回一个,
Int?
因为它可能会失败,因此请进一步检查!= nil
let something = "1" let isNumber = Int(something) != nil print(isNumber) //true because "1" can be made into an Int
注意:根据您的示例,您只检查偶数元素,因此我们将使用stride(from:to:by:)
解决方案#1:
假设你有一个String
s 数组,我们可以使用Int
初始化器来检查string
元素是否可以是数字,如下所示:
func check(expression: [String]) -> Bool {
for idx in stride(from: 0, to: expression.count, by: 2) {
let isNumeric = Int(expression[idx]) != nil
if isNumeric == false {
return false
}
}
return true
}
check(expression: ["1", "A", "2", "B", "3", "C"]) //true
check(expression: ["1", "A", "2", "B", "E", "C"]) //false
解决方案#2:
假设您的数组是类型[Any]
,并且您想要键入检查要Int
使用的备用元素is
,如下所示:
func check(expression: [Any]) -> Bool {
for idx in stride(from: 0, to: expression.count, by: 2) {
let isNumeric = expression[idx] is Int
if isNumeric == false {
return false
}
}
return true
}
check(expression: [1, "A", 2, "B", 3, "C"]) //true
check(expression: [1, "A", 2, "B", "3", "C"]) //false
问题[Any]
是它的元素不能直接提供给Int
' 的初始化程序,而不会将其变为可接受的类型。
所以在这个例子中,为了简单起见,我们只是检查对象是否完全属于类型Int
。
因此,我怀疑这是否适合您的要求。
推荐阅读
- node.js - 重新启动服务器后在服务器上重新启动 Angular + Node js 应用程序
- java - 如何在 java -simpledateformat 中将 UTC 日期转换为 PST 日期
- dynamic - 当通过更改 InputField 值开始的计算正在运行时,如何动态更新进度指示器?
- c - 来自不同 AD7606 通道的混合电压读数
- javascript - 为什么我在控制台中收到“Cross-Origin-Request-Blocked”,但路由有效?
- python - 如何根据字段与mongodb中搜索键的相关性对文档进行排序?
- python - 压缩上传的图像并使用 boto3 将其保存到 AWS S3
- flutter - 为什么我应该将返回的工厂实例设为静态字段?
- django - 是否可以使用 GeoDjango 确定到某个位置的路线及其距离?
- unreal-engine4 - 使用蓝图将二进制文件从虚幻引擎上传到 Firebase 云存储的最佳方法?