我很惊讶地发现这种情况总是成立的:
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对象是否可靠的方法?
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. }
我无法检查所有可能的情况,因此可能在某些极端情况下无法正常工作。但是据我测试,这似乎可以预期。