如何在Swift中检查变量的类型

8

我想知道初始化后的 AnyObject 变量的类型。 例如:

var test: AnyObject

test = 12.2

我不知道如何做这件事。

1个回答

12
你可以使用is运算符来实现这一点。示例代码:
var test: AnyObject

test = 12.2

if test is Double {
    println("Double type")
} else if test is Int {
    println("Int type")
} else if test is Float {
    println("Float type")
} else {
    println("Unkown type")
}

根据苹果文档:

检查类型

使用类型检查运算符(is)检查实例是否属于某个子类类型。如果实例属于该子类类型,则类型检查运算符返回true;否则返回false。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接