I use reflection and I need to test if certain members of a type are represented by a generic type. The information I want to get does not require knowing a generic signature.
How can I test types for equality?
struct A { var a: Optional<Int> }
let mirror = Mirror.init(reflecting: A(a: .some(8)))
for member in mirror.children {
type(of:member.value) == Optional<_>.self // how to do this? Any doesn't work
}
Lantua
2
I don't think you can do it. Optional<Int> has no relation with Optional<String>, and there's simply no type that encompass both (other than Any).
cukr
4
While you cannot do it directly, you can cheat by making a private protocol and making all Optional types conform to it
private protocol OptionalProtocol {}
extension Optional: OptionalProtocol {}
struct A { var a: Optional<Int> }
let mirror = Mirror.init(reflecting: A(a: .some(8)))
for member in mirror.children {
print(member.value is OptionalProtocol) // true
}
1 Like
Oh, that fits, thank you. One more question, if you don't mind: is it possible to test if a variable is a function?
cukr
6
As far as I know there is no way to do that when all you have is Any
BigSur
({ @MainActor in M1.Ultra }(Swift))
8
Is it possible to add AnyFunction to Swift?
cukr
9
Sure, but I have no idea what would it be useful for. What can you do with a function if you don't know what parameters to pass?
1 Like