在Swift中找到“ struct”类型的变量类型的正确方法是什么?

发布于 2025-01-27 18:53:45 字数 270 浏览 3 评论 0原文

截至目前,我正在使用type(of:)函数来找出变量的动态类型,并将其与type.selp.selp进行比较以检查类型:

var x = 5
if(type(of: x) == Int.self)
{
    print("\(x) is of type Int")
}

am我做对吗?还是有什么更好/优先检查类型的方法?

As of now, I am using type(of: ) function to find out the dynamic type of a variable and I compare it with Type.self to check the type :

var x = 5
if(type(of: x) == Int.self)
{
    print("\(x) is of type Int")
}

Am I doing it right ? Or is there any better/preferred way to check the type ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

谁的新欢旧爱 2025-02-03 18:53:45

如果您希望X是整数,那么我个人会使用

if(x is Int)
{
    print("\(x) is of type Int")
}

而不是使用TypeOf,因为它更可读。但是当然,您可以使用TypeOf。两者都是同样正确的

i personaly would use

if(x is Int)
{
    print("\(x) is of type Int")
}

rather than using typeof if you're expecting x to be an integer as it's far more readable. but sure, you can use typeOf if you want to. Both are equally right

我不吻晚风 2025-02-03 18:53:45

您可以使用;

if (x is Int) {
    print("\(x) is of type Int")
}

You can use;

if (x is Int) {
    print("\(x) is of type Int")
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文