首页 > 解决方案 > 检查数组值是否是 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 中的等效代码。我尝试了不同的方法,但无法解决。要求是检查数组的元素是否为数字。

标签: objective-cswift

解决方案


要检查一个对象是否是一个数字(Int在你的情况下),你可以做两件事:

  1. is通过或类型检查as?

    • 这仅检查类型而不检查内容

      let isNumberType = "1" is Int
      print(isNumberType) //false because "1" is of type String
      
  2. 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:

假设你有一个Strings 数组,我们可以使用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
因此,我怀疑这是否适合您的要求。


推荐阅读