检查`Any`值是否为对象 [英] 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.")
}
看起来无论什么类型 foo
原来,它被转换为相应类的实例。是否有可靠的方法来确定 foo
是否是对象?
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?
推荐答案
UPDATE
我在下面显示的代码报告为在版本构建中不工作。
(请参阅下面的Paul Cantrell的评论。)
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.
不确定我们可以看到这种行为在下一个测试版(或通用或发布版本...),但这是正如你期望在Xcode 8 beta 6。
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.
这篇关于检查`Any`值是否为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!