Generic Swift function to check object type

I am trying to write a function that takes an object and a type as arguments and returns a boolean indicating whether the object is of this type. There seems to be no type type, so I'm not sure how to do this. The best I could do is

func objectIsType<T>(object: AnyObject, someObjectOfType: T) -> Bool { return object is T } 

So, I can do objectIsType(x, 5) to check if x Int or objectIsType(x, "hi") to see if it is a string, but I would like to call objectIsType(x, Int) to see t22> is Int and objectIsType(x, String) to see if it is a String . Is something like this possible?

Edit:

The speed of Airspeed Velocity improved my function and made a big conclusion that it is doing what is already doing. New Feature:

 func objectIsType<T>(object: Any, someObjectOfType: T.Type) -> Bool { return object is T } 

What I'm trying to do is check that the values โ€‹โ€‹of the [String: Any] dictionary are of the type that I expect. For instance:

 let validator: [String: Any.Type] = [ "gimme an int": Int.self, "this better be a string": String.self ] let validatee: [String: Any] = [ "gimme an int": 3, "this better be a string": "it is!" ] for (key, type) in validator { if !objectIsType(validatee[key], type) { selfDestruct() } } 

But I get an error, <>protocol.Type is not convertible to T.type . I looked at the Metatype documentation, but I'm still a bit confused.

+6
source share
1 answer

If you want to specify a type as an argument, not a value, you can do the following:

 func objectIsType<T>(object: Any, someObjectOfType: T.Type) -> Bool { return object is T } let a: Any = 1 objectIsType(a, Int.self) // returns true 

NB, AnyObject can refer only to classes, and not to structures or enumerations. Int and String are structures. If you change your code, as I already above, to take Any , it also works with structures.

It would seem that your original worked without this change, but in fact it happened that interop turned your Int into NSNumber , which is a bit roundabout way of doing things and will not adapt to a method based on metatypes.

But the real question is, why do you think you need it? is already doing just that.

+2
source

Source: https://habr.com/ru/post/983713/


All Articles