3

make an assumption:

struct A{ var a:String; var b:Int }

how can i make a for loop or some other ways to get the variables names in Struct A?

2

1 Answer 1

10

Mirror is the class (it's actually a struct) for reflection in Swift. Below is a very simple example to enumerate your struct properties.

let a = A(a: "abc", b: 1)
let mirror = Mirror(reflecting: a)
for child in mirror.children {
    print(child.label!)
    print(child.value)
}

And the output will be:

a
abc
b
1

Found a post on Swift Reflection API that's worth reading: https://appventure.me/2015/10/24/swift-reflection-api-what-you-can-do/

4
  • 1
    Mirror is only suggested for Playgrounds and Debugging. It leaks memory if used in production unfortunately.
    – aBikis
    Commented Jan 31, 2017 at 23:07
  • 1
    @aBikis While the doc says "Mirrors are used by playgrounds and the debugger.", it doesn't necessarily mean they can't be used in production. Personally I doubt that reflection would be noticeably slow for light usage.
    – James Chen
    Commented Feb 1, 2017 at 4:36
  • 2
    I thought that as well! But it actually runs 3.5 X's slower! link Which isn't that big of deal but it actually created a significant number of memory leaks as well while using almost identical code to the code above. An issue that isn't documented by Apple but when used for instance as a protocol for many Structs to conform to, it ended up tanking my app.
    – aBikis
    Commented Feb 2, 2017 at 1:11
  • 1
    @aBikis Thanks for sharing your experience! Totally agree we should not use it unless it's very light usage. Memory leaks of course is another big issue.
    – James Chen
    Commented Feb 2, 2017 at 3:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.