我有一个由AnyObject组成的数组。我想遍历它,找到所有数组实例的元素。

我怎么能检查如果一个对象是一个给定的类型在Swift?


当前回答

为什么不使用专门为此任务构建的内置功能呢?

let myArray: [Any] = ["easy", "as", "that"]
let type = type(of: myArray)

Result: "Array<Any>"

其他回答

在Swift 2.2 - 5你现在可以做:

if object is String
{
}

然后过滤你的数组:

let filteredArray = originalArray.filter({ $0 is Array })

如果你有多个类型需要检查:

    switch object
    {
    case is String:
        ...

    case is OtherClass:
        ...

    default:
        ...
    }

为什么不用这样的东西呢

fileprivate enum types {
    case typeString
    case typeInt
    case typeDouble
    case typeUnknown
}

fileprivate func typeOfAny(variable: Any) -> types {
    if variable is String {return types.typeString}
    if variable is Int {return types.typeInt}
    if variable is Double {return types.typeDouble}
    return types.typeUnknown
}

在Swift 3中。

为什么不使用专门为此任务构建的内置功能呢?

let myArray: [Any] = ["easy", "as", "that"]
let type = type(of: myArray)

Result: "Array<Any>"

Swift 5.2 & Xcode版本:11.3.1(11C504)

以下是我检查数据类型的解决方案:

 if let typeCheck = myResult as? [String : Any] {
        print("It's Dictionary.")
    } else { 
        print("It's not Dictionary.") 
    }

我希望它能帮助你。

如果你只是想检查类而不得到警告,因为未使用的定义值(let somvariable…),你可以简单地用一个布尔值替换let:

if (yourObject as? ClassToCompareWith) != nil {
   // do what you have to do
}
else {
   // do something else
}

Xcode在我使用let方法而没有使用定义值时提出了这个建议。