How do you find out the type of an object (in 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 中)?
基础教程推荐
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01