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

我如何知道Swift中的一个实例变量的类,第1张

概述有什么简单的方法可以告诉Swift中的实例变量是什么类型的?在我习惯的基于JVM的语言中,你可以像println(value.class)这样做来获得它的类。 在Swift有什么相当的东西吗? 在文档中可以找到最接近的东西是使用is <Class> keyword进行“类型检查”的能力,但这只能帮助我猜一下。 我已经遇到了一个few situations,在那里我认为我有一种类型的课,但实际上有另 有什么简单的方法可以告诉Swift中的实例变量是什么类型的?在我习惯的基于JVM的语言中,你可以像println(value.class)这样做来获得它的类。

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

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

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

@H_301_8@ 使用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.

总结

以上是内存溢出为你收集整理的我如何知道Swift中的一个实例变量的类全部内容,希望文章能够帮你解决我如何知道Swift中的一个实例变量的类所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1052645.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-25
下一篇 2022-05-25

发表评论

登录后才能评论

评论列表(0条)

保存