我惊讶地发现这种情况总是如此:
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.")
}
Run Code Online (Sandbox Code Playgroud)
似乎无论foo
最初是什么类型,它都被转换为相应类的实例.有没有可靠的方法来确定是否foo
是一个对象?
据报告,我在下面显示的代码在发布版本中不起作用。(请参阅下面 Paul Cantrell 的评论。)
对我的“据我测试”的歉意太有限了。
当我找到有关此问题的更多信息时,我会更新此答案。
我不确定我们能否在下一个 beta(或 GM 或已发布版本...)中看到这种行为,但这在 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.
}
Run Code Online (Sandbox Code Playgroud)
我无法检查所有可能的情况,因此可能存在一些边缘情况,这不起作用。但据我测试,这似乎按预期工作。
归档时间: |
|
查看次数: |
926 次 |
最近记录: |