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

问题描述

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



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

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

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



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

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



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

由于 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:

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

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动态类型检查结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 21:31