Reputation: 4376
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
}
}
Upvotes: 1
Views: 318
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