Tomas Jablonskis
Tomas Jablonskis

Reputation: 4376

Is there a way to check if a delegate is a value or a reference type?

Lets say we had something like this:

protocol Delegate {}

struct Value: Delegate {}
class Reference: Delegate {}

struct Test {
    let delegate: Delegate
}

How could we know if a delegate is a struct (value type) or a class (reference type)?

First thought that comes to mind is to check memory address equality after making a copy of a delegate:

struct Test {
    let delegate: Delegate

    var isReferenceType: Bool {
        let copy = delegate

        let copyAddress = // ... get memory address of a copy
        let originalAddress = // ... get memory address of an original

        return copyAddress == originalAddress
    }
}

  1. Is it even possible to do this?
  2. Is there more elegant/correct way of doing this?
  3. Copying a value type might potentially be an expensive operation?

Upvotes: 1

Views: 318

Answers (1)

πter
πter

Reputation: 2217

Every class conforms to the AnyClass protocol. However enums and structs won't. Utilising that you can check if it's a class or a struct(or even an enum)

struct Test {
    let delegate: Delegate

    var isReferenceType: Bool {
        return type(of:delegate) is AnyClass
    }
}

Upvotes: 3

Related Questions