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.
Types in Swift fall into one of two categories: first, “value types”, where each instance keeps a unique copy of its data, usually defined as a struct, enum, or tuple. The second, “reference types”, where instances share a single copy of the data, and the type is usually defined as a class.
In Swift, instances of classes are passed by reference. This is similar to how classes are implemented in Ruby and Objective-C. It implies that an instance of a class can have several owners that share a copy. Instances of structures and enumerations are passed by value.
Value Type — each instance keeps a unique copy of its data. A type that creates a new instance (copy) when assigned to a variable or constant, or when passed to a function. Reference Type — each instances share a single copy of the data.
System. Enum is a reference type, but any specific enum type is a value type. In the same way, System. ValueType is a reference type, but all types inheriting from it (other than System.
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 5
func isReferenceType(_ toTest: Any) -> Bool {
return type(of: toTest) is AnyClass
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With