Swift动态类型检查结构? [英] Swift dynamic type checking for structs?

查看:190
本文介绍了Swift动态类型检查结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Swift中的动态类型检查感到困惑。



具体来说,我有一个奇怪的情况,我本来想写(或查找)一个函数:

  func isInstanceOf(obj:Any,type:Any.Type) - > Bool 

在Objective-C中,这是 isKindOfClass ,但这不会工作,因为 Any.Type 包括Swift结构,不是类(更不用说 NSObject 子类)



我不能在这里使用Swift ,因为这需要硬编码类型。 >

我不能使用 obj.dynamicType == type ,因为这将忽略子类。



Swift书籍似乎建议这些信息丢失,并且根本不可用于结构体:


类具有附加功能,结构不: / p>

...




  • 类型转换使您能够检查和解释运行时的一个类实例。


其他语言)。



但是,由于不能使用,因为不适用于结构,所以不可能可以将Strings和Ints放入 [Any] 中,然后将它们拉出来,使用为String 是Int 来弄清楚它们是什么。 Swift Book的类型铸造章节正是这样!



有没有一些与 isKindOfClass 一样强大的东西,但是任何Swift实例?

解决方案

其实你可以使用运算符。


使用类型检查运算符(是)检查实例是否具有某种子类型。如果实例是该子类型,则类型检查运算符返回true,否则为false。


由于 struct 不能被子类化,被保证在应用于struct的实例时是一致的,因为它会检查它的静态类型,对于类,它将在运行时查询动态类型。

  func`is`< T>(实例: :T.Type) - > Bool {
return instance is T;
}

这项工作适用于 struct class


I'm confused about dynamic type checking in Swift.

Specifically, I have a weirdo case where I want to, essentially, write (or find) a function:

func isInstanceOf(obj: Any, type: Any.Type) -> Bool

In Objective-C, this is isKindOfClass, but that won't work because Any.Type includes Swift structs, which are not classes (much less NSObject subclasses).

I can't use Swift is here, because that requires a hardcoded type.

I can't use obj.dynamicType == type because that would ignore subclasses.

The Swift book seems to suggest that this information is lost, and not available for structs at all:

Classes have additional capabilities that structures do not:

...

  • Type casting enables you to check and interpret the type of a class instance at runtime.

(On the Type Casting chapter, it says "Type casting in Swift is implemented with the is and as operators", so it seems to be a broader definition of "type casting" than in other languages.)

However, it can't be true that is/as don't work with structures, since you can put Strings and Ints into an [Any], and pull them out later, and use is String or is Int to figure out what they were. The Type Casting chapter of the Swift Book does exactly this!

Is there something that's as powerful as isKindOfClass but for any Swift instances? This information still must exist at runtime, right?

解决方案

Actually you can use is operator.

Use the type check operator (is) to check whether an instance is of a certain subclass type. The type check operator returns true if the instance is of that subclass type and false if it is not.

Since struct can't be subclassed, is is guaranteed to be consistent when applied to instance of struct because it will check on it static type, and for classes it will query the dynamic type in runtime.

func `is`<T>(instance: Any, of kind: T.Type) -> Bool{
   return instance is T;
}

This work for both, struct and class.

这篇关于Swift动态类型检查结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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