swift - Swift 3.0 中如何区分类(确定它不是结构体或枚举)

标签 swift xcode swift3 value-type reference-type

<分区>

如何判断实例是值类型还是引用类型?

描述:

首先,我在 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

enter image description here

甚至更多......我能够将我的结构设置为 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 中运行良好(如我所想)。

无论如何感谢您的关注

最佳答案

简短的回答是:

type(of: value) is AnyClass

关于swift - Swift 3.0 中如何区分类(确定它不是结构体或枚举),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43232025/

相关文章:

ios - 将值传递给 api 时得到 nil 值

swift - 在 Swift 中使用 JSONModel 解析自定义模型数组

ios - centralManager 方法未被调用

swift - 导航 Controller 未释放内存,内存泄漏?

swift - Completion 很快就会被调用

swift - 观看操作系统 : Microphone & Audio Processing

arrays - 将旧的 C for 循环更改为新的 Swift 循环

ios - 使用 StoryBoard Reference 时如何获取 UITabBarItem 的图像值?

ios - 将图像旋转 3*Double.pi/2 使图像不出现 (swift3)

ios - 类型的值没有成员值Swift 3给出错误