Checking if an object is a given type in Swift

匿名 (未验证) 提交于 2019-12-03 02:49:01

问题:

I have an array that is made up of AnyObject. I want to iterate over it, and find all elements that are array instances.

How can I check if an object is of a given type in Swift?

回答1:

If you want to check against a specific type you can do the following:

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

You can use "as!" and that will throw a runtime error if obj is not of type [String]

let stringArray = obj as! [String] 

You can also check one element at a time:

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


回答2:

If you only want to know if an object is a subtype of a given type then there is a simpler approach:

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

“Use the type check operator (is) to check whether an instance is of a certain subclass type. The type check operator returns true if the instance is of that subclass type and false if it is not.” Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks.

In the above the phrase 'of a certain subclass type' is important. The use of is Circle and is Rectangle is accepted by the compiler because that value shape is declared as Shape (a superclass of Circle and Rectangle).

If you are using primitive types, the superclass would be Any. Here is an example:

 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" 


回答3:

In Swift 2.2 - 4.0.3 you can now do:

if object is String { } 

Then to filter your array:

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


回答4:

I have 2 ways of doing it:

if let thisShape = aShape as? Square  

Or:

aShape.isKindOfClass(Square) 

Here is a detailed example:

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

Edit: 3 now:

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


回答5:

Assume drawTriangle is an instance of UIView.To check whether drawTriangle is of type UITableView:

In Swift 3,

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

This also could be used for classes defined by yourself. You could use this to check subviews of a view.



回答6:

for swift4:

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


回答7:

Why not use the built in functionality built especially for this task?

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


回答8:

Be warned about this:

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)  

All of the four last lines return true, this is because if you type

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

... it prints "false" of course, but a Warning says that the Cast from CGRect to String fails. So some type are bridged, ans the 'is' keyword calls an implicit cast.

You should better use one of these:

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


回答9:

If you just want to check the class without getting a warning because of the unused defined value (let someVariable ...), you can simply replace the let stuff with a boolean:

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

Xcode proposed this when I used the let way and didn't use the defined value.



回答10:

Why not to use something like this

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 } 

in Swift 3.



回答11:

Swift 3:

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


回答12:

myObject as? String returns nil if myObject is not a String. Otherwise, it returns a String?, so you can access the string itself with myObject!, or cast it with myObject! as String safely.



回答13:

If you have Response Like This:

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

and you want to check for value is_stucked which will be read as AnyObject, all you have to do is this

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!