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

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

问题描述

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

dynamicType(参见这个问题)

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

这个看起来最有前途,但目前我还没有找到实际的类型.

class MyClass {变量计数 = 0}让 mc = MyClass()# 更新:现在评估为真mc.dynamicType === MyClass.self

我还尝试使用类引用来实例化一个新对象,确实有效,但奇怪的是给了我一个错误,说我必须添加一个 required 初始值设定项:

作品:

class MyClass {变量计数 = 0必需的 init() {}}让 myClass2 = MyClass.self让 mc2 = MyClass2()

仍然只是实际发现任何给定对象的类型的一小步

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

解决方案

Swift 3 版本:

type(of: yourObject)

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()

dynamicType (see this question)

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

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:

works:

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 version:

type(of: yourObject)

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆