frangulyan frangulyan - 1 year ago 42
Swift Question

Check whether Swift object is an instance of a given metatype

I need to keep a collection of Swift metatypes and write a function which will check if a given object is an instance of one of them. I can do that easily in Java:

Class c = x.getClass();

However, I have no idea how to do that in Swift:

var isInt = 7 is Int.Type // compiles

let x = Int.self
var isInt = 7 is x // compiler error - Use of undeclared type 'x'

Is this even possible to be done in Swift?

Answer Source

Ideally the following should work in your case with some changes as type(of: 7) instead of 7 and == operator instead of is. But swift has a bug which throws following error.

let x = Int.self
var isInt = type(of: 7) == x //binary operator '==' cannot be applied to two 'Int.Type' operands

Instead you can use the following code and it will work fine.

let x = Int.self
var typeOfX = type(of: 7)
var isInt = typeOfX == x //true

Apple engineers have confirmed this bug here:

Joe Groff - Twitter

First line in your question should be var isInt = 7 is Int. Notice Int instead of Int.Type. Otherwise Xcode will throw below warning.

enter image description here

Usually in most cases you could just do,

if z is String {
   //do something
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download