是否可以像在C#中一样检查Swift中的类型?

时间:2016-04-28 05:10:52

标签: swift swift2

在Swift中可以这样做吗?

if (obj1.GetType() == obj2.GetType()) { /* do something */}

1 个答案:

答案 0 :(得分:1)

您可以使用此问题中提到的Mirror结构 How do you find out the type of an object (in Swift)?
这里举几个例子:

let var1 = "Test"
let var2 = "Hello World"
let var3 = UIView()
let var4 = UIView(frame: CGRect.zero)

let mirror1 = Mirror(reflecting: var1)
let mirror2 = Mirror(reflecting: var2)
let mirror3 = Mirror(reflecting: var3)
let mirror4 = Mirror(reflecting: var4)

print(mirror1.subjectType == mirror2.subjectType) // true
print(mirror2.subjectType == mirror3.subjectType) // false
print(mirror3.subjectType == mirror4.subjectType) // true