andyvn22 andyvn22 - 3 months ago 10
Swift Question

Check if `Any` value is object

I was surprised to find that this condition is always true:

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


It seems that no matter what type
foo
was originally, it is converted to an instance of a corresponding class. Is there a reliable way to determine whether or not
foo
is an object?

Answer

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.