Type equality

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
}

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).

Nice :expressionless:

Goodbye swift...

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?

As far as I know there is no way to do that when all you have is Any

https://github.com/wickwirew/Runtime may help you

1 Like

Is it possible to add AnyFunction to Swift?

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
Terms of Service

Privacy Policy

Cookie Policy