zaitsman
zaitsman

Reputation: 9509

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.

Upvotes: 5

Views: 1408

Answers (2)

Muzahid
Muzahid

Reputation: 5186

Apple developer documentation says:

Mirror is a representation of the substructure and display style of an instance of any type.

(https://developer.apple.com/documentation/swift/mirror)

So you can apply mirror on instance. That's why children property is empty.

Mirror(reflecting: MyBanana()).children.count // return 1

Upvotes: 2

Alexander
Alexander

Reputation: 63321

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.

Upvotes: 4

Related Questions