简体   繁体   English

如何比较 Swift 中的类型?

[英]How to compare types in Swift?

I declare two variables in a Swift file, with the following values:我在 Swift 文件中声明了两个变量,其值如下:

let m = 1
let n = 2

Now, I would like to compare their types:现在,我想比较它们的类型:

type(of: m) === type(of: n)

The following compliling error occurs:出现以下编译错误:

Argument type 'String.Type' expected to be an instance of a class or class-constrained type

Is there a way to compare types?有没有办法比较类型?

Also, why does this line fail?另外,为什么这条线会失败?

String === String

The === operator is only defined for reference types, since it checks reference (pointer) equality, so you can't use it on metatypes of value types. ===运算符只为引用类型定义,因为它检查引用(指针)是否相等,所以你不能在值类型的元类型上使用它。

However, you can use the normal equality operator, == .但是,您可以使用正常的相等运算符==

type(of: m) == type(of: n)

As for String === String , that's not even valid code.至于String === String ,那甚至不是有效的代码。 What you need if String.self == String.self .如果String.self == String.self你需要什么。 You can access metatypes using TypeName.self .您可以使用TypeName.self访问元类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM