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

我如何知道Swift中的一个实例变量的类

发布时间:2020-12-14 05:51:10 所属栏目:百科 来源:网络整理
导读:有什么简单的方法可以告诉Swift中的实例变量是什么类型的?在我习惯的基于JVM的语言中,你可以像println(value.class)这样做来获得它的类。 在Swift有什么相当的东西吗? 在文档中可以找到最接近的东西是使用 is Class keyword进行“类型检查”的能力,但这
有什么简单的方法可以告诉Swift中的实例变量是什么类型的?在我习惯的基于JVM的语言中,你可以像println(value.class)这样做来获得它的类。

在Swift有什么相当的东西吗?

在文档中可以找到最接近的东西是使用is <Class> keyword进行“类型检查”的能力,但这只能帮助我猜一下。

我已经遇到了一个few situations,在那里我认为我有一种类型的课,但实际上有另一种,不知道如何知道肯定。

使用type.self返回一个可以传递给接受类型参数的方法的类型。例如,UILabel.self可以传递给isKindOfClass方法调用。该类的字符串表示可以通过dynamicType.description()找到:
var label = UILabel()
println(label.dynamicType.description())
println(label.isKindOfClass(UILabel.self))

斯威夫特-3

var label = UILabel()
println(type(of: label).description())

Output
UILabel
true

这里有更多的背景 – 有两个表达式要注意:后缀自我表达式和动态类型表达式。从the docs:

Postfix Self
A postfix self expression consists of an expression or the name of a
type,immediately followed by .self. It has the following forms:

06002

The first form evaluates to the value of the expression. For example,
x.self evaluates to x.

The second form evaluates to the value of the type. Use this form to
access a type as a value. For example,because SomeClass.self
evaluates to the SomeClass type itself,you can pass it to a function
or method that accepts a type-level argument

Dyamic Type Expression

A dynamicType expression consists of an expression,immediately
followed by .dynamicType. It has the following form:

06003

The expression can’t be the name of a type. The entire dynamicType expression evaluates to the value of the runtime type of the expression.

(编辑:李大同)

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

    推荐文章
      热点阅读