Check if `Any` value is object

UPDATE

The code I have shown below is reported as not working in release build.
(Please see Paul Cantrell’s comment below.)

Apologies for my “as far as I tested” was too limited.

I’ll update this answer when I find some further info about this.


I’m not sure we can see this behaviour in the next beta (or GM or Released version…), but this works as you expect in Xcode 8 beta 6.

let foo: Any = 4
if type(of: foo) is AnyClass {
    print("It's an object.")
    let object = foo as AnyObject
    //do something with `object` that requires reference semantics
} else {
    print("It's not an object.") //->It's not an object.
}

class MyClass {}
let bar: Any = MyClass()
if type(of: bar) is AnyClass {
    print("It's an object.") //->It's an object.
    let object = foo as AnyObject
    //do something with `object` that requires reference semantics
} else {
    print("It's not an object.")
}

let baz: Any = Array<AnyObject>()
if type(of: baz) is AnyClass {
    print("It's an object.")
    let object = foo as AnyObject
    //do something with `object` that requires reference semantics
} else {
    print("It's not an object.") //->It's not an object.
}

I cannot check all possible cases, so there may be some edge cases where this does not work. But as far as I tested, this seems to work as expected.

Leave a Comment