在Swift中检查值或引用类型 [英] Check for value or reference type in Swift

查看:133
本文介绍了在Swift中检查值或引用类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何检查在函数中传递的参数是值还是引用类型?例如

How can we check if a parameter passed in a function is a value or a reference type? For example

func isReferenceType(toTest: Any) {
    return true // or false
}

我们在在此处看到,我们无法利用泛型来做到这一点.

As we see here, we are not able to do this leveraging generics.

推荐答案

AnyObject是任何类类型都会自动遵循的协议,因此您可以编写:

AnyObject is a protocol that any class type automatically conforms to, so you can write:

func isReferenceType(toTest: Any) -> Bool {
    return toTest.dynamicType is AnyObject
}

class Foo { }
struct Bar { }

isReferenceType(Foo())    // true
isReferenceType(Bar())    // false
isReferenceType("foo")    // false
isReferenceType(123)      // false
isReferenceType([1,2,3])  // false

这篇关于在Swift中检查值或引用类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆