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 中)?


- Android - 我如何找出用户有多少未读电子邮件? 2022-01-01
- 用 Swift 实现 UITextFieldDelegate 2022-01-01
- android 4中的android RadioButton问题 2022-01-01
- 在测试浓缩咖啡时,Android设备不会在屏幕上启动活动 2022-01-01
- MalformedJsonException:在第1行第1列路径中使用JsonReader.setLenient(True)接受格式错误的JSON 2022-01-01
- 想使用ViewPager,无法识别android.support.*? 2022-01-01
- 使用自定义动画时在 iOS9 上忽略 edgesForExtendedLayout 2022-01-01
- Android viewpager检测滑动超出范围 2022-01-01
- Android - 拆分 Drawable 2022-01-01
- 如何检查发送到 Android 应用程序的 Firebase 消息的传递状态? 2022-01-01