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

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


如果你想检查一个特定的类型,你可以做以下事情:

if let stringArray = obj as? [String] {
    // obj is a string array. Do something with stringArray
}
else {
    // obj is not a string array
}

你可以使用"as!",如果obj不是[String]类型,就会抛出一个运行时错误。

let stringArray = obj as! [String]

你也可以一次检查一个元素:

let items : [Any] = ["Hello", "World"]
for obj in items {
   if let str = obj as? String {
      // obj is a String. Do something with str
   }
   else {
      // obj is not a String
   }
}

如果你只想知道一个对象是否是给定类型的子类型,那么有一个更简单的方法:

class Shape {}
class Circle : Shape {}
class Rectangle : Shape {}

func area (shape: Shape) -> Double {
  if shape is Circle { ... }
  else if shape is Rectangle { ... }
}

"使用类型检查操作符(is)来检查实例是否属于某个类型 子类的类型。如果实例为,则类型检查操作符返回true 如果不是,则为false "摘自:苹果公司《快速编程语言》。“iBooks。

在上面的句子中,“of a certain subclass type”很重要。is Circle和is Rectangle的使用被编译器接受,因为该值shape被声明为shape (Circle和Rectangle的超类)。

如果您使用的是基本类型,超类将是Any。这里有一个例子:

 21> func test (obj:Any) -> String {
 22.     if obj is Int { return "Int" }
 23.     else if obj is String { return "String" }
 24.     else { return "Any" }
 25. } 
 ...  
 30> test (1)
$R16: String = "Int"
 31> test ("abc")
$R17: String = "String"
 32> test (nil)
$R18: String = "Any"

myObject一样吗?如果myObject不是String, String返回nil。否则,它返回一个字符串?,所以你可以使用myObject访问字符串本身!,或者使用myObject强制转换它!作为字符串安全。

我有两种方法:

if let thisShape = aShape as? Square 

Or:

aShape.isKindOfClass(Square)

下面是一个详细的例子:

class Shape { }
class Square: Shape { } 
class Circle: Shape { }

var aShape = Shape()
aShape = Square()

if let thisShape = aShape as? Square {
    println("Its a square")
} else {
    println("Its not a square")
}

if aShape.isKindOfClass(Square) {
    println("Its a square")
} else {
    println("Its not a square")
}

编辑:3现在:

let myShape = Shape()
if myShape is Shape {
    print("yes it is")
}

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

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

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

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

if object is String
{
}

然后过滤你的数组:

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

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

    switch object
    {
    case is String:
        ...

    case is OtherClass:
        ...

    default:
        ...
    }

如果你有这样的响应:

{
  "registeration_method": "email",
  "is_stucked": true,
  "individual": {
    "id": 24099,
    "first_name": "ahmad",
    "last_name": "zozoz",
    "email": null,
    "mobile_number": null,
    "confirmed": false,
    "avatar": "http://abc-abc-xyz.amazonaws.com/images/placeholder-profile.png",
    "doctor_request_status": 0
  },
  "max_number_of_confirmation_trials": 4,
  "max_number_of_invalid_confirmation_trials": 12
}

你想检查值is_stuck将被读取为AnyObject,你所要做的就是这个

if let isStucked = response["is_stucked"] as? Bool{
  if isStucked{
      print("is Stucked")
  }
  else{
      print("Not Stucked")
 }
}

假设drawTriangle是UIView的一个实例。检查drawTriangle是否为UITableView类型:

在Swift 3中,

if drawTriangle is UITableView{
    // in deed drawTriangle is UIView
    // do something here...
} else{
    // do something here...
}

这也可以用于你自己定义的类。你可以用它来检查视图的子视图。

为什么不用这样的东西呢

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>"

请注意:

var string = "Hello" as NSString
var obj1:AnyObject = string
var obj2:NSObject = string

print(obj1 is NSString)
print(obj2 is NSString)
print(obj1 is String)
print(obj2 is String) 

最后四行都返回true,这是因为如果你输入

var r1:CGRect = CGRect()
print(r1 is String)

... 它打印“假”当然,但警告说,Cast从CGRect到字符串失败。因此有些类型是桥接的,'is'关键字调用隐式强制转换。

你最好使用其中的一个:

myObject.isKind(of: MyClass.self)) 
myObject.isMember(of: MyClass.self))

斯威夫特3:

class Shape {}
class Circle : Shape {}
class Rectangle : Shape {}

if aShape.isKind(of: Circle.self) {
}

swift4:

if obj is MyClass{
    // then object type is MyClass Type
}

如果您不知道您将从服务器的响应中获得一个字典数组或单个字典,则需要检查结果是否包含数组。 在我的情况下,总是接收一个字典数组,除了一次。所以,为了处理这个问题,我使用了下面的swift 3代码。

if let str = strDict["item"] as? Array<Any>

在这里吗?Array检查获取的值是否为Array(字典项)。在其他情况下,你可以处理,如果它是一个字典项,而不是保存在数组中。

Swift 4.2,在我的情况下,使用isKind函数。

isKind (:) 返回一个布尔值,该值指示接收者是给定类的实例还是从该类继承的任何类的实例。

  let items : [AnyObject] = ["A", "B" , ... ]
  for obj in items {
    if(obj.isKind(of: NSString.self)){
      print("String")
    }
  }

阅读更多 https://developer.apple.com/documentation/objectivec/nsobjectprotocol/1418511-iskind

只是为了完整起见,基于公认的答案和其他一些答案:

let items : [Any] = ["Hello", "World", 1]

for obj in items where obj is String {
   // obj is a String. Do something with str
}

但是你也可以(compactMap也“映射”过滤器没有的值):

items.compactMap { $0 as? String }.forEach{ /* do something with $0 */ ) }

以及一个使用switch的版本:

for obj in items {
    switch (obj) {
        case is Int:
           // it's an integer
        case let stringObj as String:
           // you can do something with stringObj which is a String
        default:
           print("\(type(of: obj))") // get the type
    }
}

但回到问题上来,检查它是否是一个数组(即[String]):

let items : [Any] = ["Hello", "World", 1, ["Hello", "World", "of", "Arrays"]]

for obj in items {
  if let stringArray = obj as? [String] {
    print("\(stringArray)")
  }
}

或者更一般地说(见另一个问题的答案):

for obj in items {
  if obj is [Any] {
    print("is [Any]")
  }

  if obj is [AnyObject] {
    print("is [AnyObject]")
  }

  if obj is NSArray {
    print("is NSArray")
  }
}

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.") 
    }

我希望它能帮助你。

是吗?不会总是给出预期的结果,因为as并不测试数据类型是否为特定类型,而只测试数据类型是否可以转换为或表示为特定类型。

以下面的代码为例:

func handleError ( error: Error ) {
    if let nsError = error as? NSError {

每个符合Error协议的数据类型都可以转换为NSError对象,所以这总是会成功。但这并不意味着error实际上是一个NSError对象或它的子类。

正确的类型检查应该是:

func handleError ( error: Error ) {
    if type(of: error) == NSError.self {

但是,这只检查确切的类型。如果你还想包含NSError的子类,你应该使用:

func handleError ( error: Error ) {
    if error is NSError.Type {
let originalArray : [Any?] = ["Hello", "World", 111, 2, nil, 3.34]
let strings = originalArray.compactMap({ $0 as? String })

print(strings)
//printed: ["Hello", "World"]

你可以使用这个函数,然后调用它:

func printInfo(_ value: Any) {
    let t = type(of: value)
    print("'\(value)' of type '\(t)'")
}

例如:printInfo(data)

数据类型为“125字节”