加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

结构的Swift动态类型检查?

发布时间:2020-12-14 05:39:31 所属栏目:百科 来源:网络整理
导读:我对 Swift中的动态类型检查感到困惑. 具体来说,我有一个怪异的情况,我想在本质上写一个(或找到)一个函数: func isInstanceOf(obj: Any,type: Any.Type) - Bool 在Objective-C中,这是isKindOfClass,但这不起作用,因为Any.Type包含Swift结构,它不是类(更不用
我对 Swift中的动态类型检查感到困惑.

具体来说,我有一个怪异的情况,我想在本质上写一个(或找到)一个函数:

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

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

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

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

Swift book似乎表明此信息丢失,根本不适用于结构:

Classes have additional capabilities that structures do not:

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

(在Type Casting一章中,它说“Swift中的类型转换是使用is和as运算符实现的”,因此它似乎是比“in other languages”更广泛的“类型转换”定义.)

但是,因为你不能使用结构,因为你可以将字符串和Ints放入[Any]中,然后将它们拉出来,并使用String或Int来弄清楚它们是什么是. Swift Book的Type Casting章节正是这样做的!

有什么东西和isKindOfClass一样强大,但是对于任何Swift实例?这些信息仍然必须在运行时存在,对吧?

实际上你可以使用is运算符.

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.

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

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

这对结构和类都有效.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读