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?
Basically, we check if a value is object-like using typeof, instanceof, constructor, and Object. prototype. toString. call(k).
To check if all values in object are equal to true :Use the Object. values() method to get an array of the object's values. Call the every() method on the array. The every method will test if all values in the array are equal to true and will return the result.
Method 1: Using the typeof operator The typeof operator returns the type of the variable on which it is called as a string. The return string for any object that does not exist is “undefined”. This can be used to check if an object exists or not, as a non-existing object will always return “undefined”.
You can check object type in Java by using the instanceof keyword. Determining object type is important if you're processing a collection such as an array that contains more than one type of object. For example, you might have an array with string and integer representations of numbers.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With