<分区>
如何判断实例是值类型还是引用类型?
描述:
首先,我在 the documentation 中读到了有关 AnyObject 的信息.
Swift provides two special types for working with nonspecific types:
Any can represent an instance of any type at all, including function types.:
AnyObject can represent an instance of any class type.
Use Any and AnyObject only when you explicitly need the behavior and capabilities they provide. It is always better to be specific about the types you expect to work with in your code.
所以我决定在我的 Playground 中编写一些简单的代码:
struct MyStruct {
var x = 5
}
let testStruct = MyStruct()
testStruct is AnyObject
if let object = testStruct as? AnyObject {
//Do something
}
当看到 2 个警告时,我感到很震惊。
- 'is' test is always true
- Conditional cast from 'MyStruct' to 'AnyObject' always succeedstestStruct is AnyObject
甚至更多......我能够将我的结构设置为 weak 属性。
class TestClass {
weak var object: AnyObject?
}
var instance: TestClass? = TestClass()
instance?.object = testStruct as AnyObject
而且我还没有看到任何警告或错误。它会导致崩溃或未定义的行为吗?这对我来说看起来很奇怪......
我还提到了 playground 中的类型。
- type(of: testStruct as AnyObject) - _SwiftValue.Type
- type(of: testStruct) - MyStruct.Type
可能 testStruct 被隐式转换为类。但是我不确定,也不能在互联网上找到任何关于它的信息 =(
你读过有关它的资料吗?或者你能给我一些文档链接以了解发生了什么。可能我错过了非常重要的事情。
- Swift 版本:Apple Swift 版本 3.0.2 (swiftlang-800.0.63 clang-800.0.42.1)
- XCode 版本:8.2.1 (8C1002)
附言
我必须强调它在 Swift 2.0 中运行良好(如我所想)。
无论如何感谢您的关注