Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Mirror Children collection empty when reflecting a type

I am trying to get a list of all properties on a struct.

I used this code:

struct MyBanana {
    var b: String?
}

Mirror(reflecting: MyBanana.self).children.isEmpty // returns true

Why is my .children collection empty?

I need to be able to get these from a type rather than an instance.

like image 514
zaitsman Avatar asked Jul 29 '19 02:07

zaitsman


1 Answers

I need to be able to get these from a type rather than an instance.

You can't. Swift's reflection story hasn't been fleshed out. The runtime metadata that's necessary for reflection has been present in Swift for a very long time. It's heavily relied upon by Xcode, the LLVM debugger and Instruments, but it was too frequently changing to make sense to build an API over it.

I expect reflection will be addressed somewhat soon, now that ABI stability has been established. Until then, are multiple third-party reflection libraries out there that you can use. Their authors had reverse engineered the runtime metadata, and built an API over it. You just have to make sure that the library has been updated since Swift 5.

like image 50
Alexander Avatar answered Sep 29 '22 20:09

Alexander