检查“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.
我不确定我们能否在下一个测试版(或 GM 或已发布版本...)中看到这种行为,但这在 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屋!