Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for value or reference type in 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.

like image 700
Michael Dorner Avatar asked Jan 11 '16 15:01

Michael Dorner


People also ask

Is Swift reference type or value type?

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.

Is Swift pass by reference or value?

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.

What is value type and reference type in IOS?

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.

Is enum value type or reference Swift?

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.


2 Answers

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
like image 60
Nate Cook Avatar answered Oct 11 '22 13:10

Nate Cook


Swift 5

func isReferenceType(_ toTest: Any) -> Bool {
    return type(of: toTest) is AnyClass
}
like image 5
iUrii Avatar answered Oct 11 '22 12:10

iUrii