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.
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
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
isReferenceType("foo")
or isReferenceType(123)
or isReferenceType([1, 2, 3])
will also return true
(if Foundation is imported). –
Banda func isReferenceType<T: Any>(toTest: T) -> Bool { return !(T.self is AnyObject) }
–
Itemized Swift 5
func isReferenceType(_ toTest: Any) -> Bool {
return type(of: toTest) is AnyClass
}
© 2022 - 2024 — McMap. All rights reserved.
is AnyObject
? – Whippletree