你如何找出对象的类型(在 Swift 中)?

How do you find out the type of an object (in Swift)?(你如何找出对象的类型(在 Swift 中)?)

本文介绍了你如何找出对象的类型(在 Swift 中)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当试图理解一个程序时,或者在某些极端情况下,找出某个东西是什么类型是很有用的.我知道调试器可以向您显示一些类型信息,并且您通常可以依靠类型推断来避免在这些情况下不指定类型,但是,我真的很想拥有类似 Python 的 type()

When trying to understand a program, or in some corner-cases, it's useful to find out what type something is. I know the debugger can show you some type information, and you can usually rely on type inference to get away with not specifying the type in those situations, but still, I'd really like to have something like Python's type()

更新:这在最近的 Swift 版本中有所改变,obj.dynamicType 现在为您提供类型的引用,而不是动态类型的实例.

Update: this has been changed in a recent version of Swift, obj.dynamicType now gives you a reference to the type and not the instance of the dynamic type.

这个似乎最有前途,但我至今没能找到真正的类型.

This one seems the most promising, but I haven't been able to find out the actual type so far.

class MyClass {
    var count = 0
}

let mc = MyClass()

# update: this now evaluates as true
mc.dynamicType === MyClass.self

我还尝试使用类引用来实例化一个新对象,确实可以工作,但奇怪的是给了我一个错误,说我必须添加一个 required 初始化程序:

I also tried using a class reference to instantiate a new object, which does work, but oddly gave me an error saying I must add a required initializer:

作品:

class MyClass {
    var count = 0
    required init() {
    }
}

let myClass2 = MyClass.self
let mc2 = MyClass2()

尽管离真正发现任何给定对象的类型只有一小步

Still only a small step toward actually discovering the type of any given object though

编辑:我已经删除了大量现在不相关的细节 - 如果您有兴趣,请查看编辑历史:)

edit: I've removed a substantial number of now irrelevant details - look at the edit history if you're interested :)

推荐答案

Swift 3 版本:

type(of: yourObject)

这篇关于你如何找出对象的类型(在 Swift 中)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:你如何找出对象的类型(在 Swift 中)?

基础教程推荐