Convert variable names into dictionary keys?

Hi guys, hope you all going well.

Long words short, let's say i have array of UIView like

let someButton:Button(.system)
let someLabel;UILabel()
let views = [somebutton,someLabel]

How i can convert them into dictionary like
[
"someButton":someButton,
"someLabel": someLabel
]

My problem is recover variable name from object. Thanks for help. Seems my google-fu too weak

You’ll need some kind of reflection. Swift does it with Mirror.

Try:

let mirror = Mirror(reflecting: view)

let variableList: [(String, Any)] = mirror.children.compactMap {
    guard let label = $0.label else { return nil }
    return (label, $0.value)
}
let dictionary = Dictionary(uniqueKeysWithValues: variableList)

let variableNames = mirror.children.compactMap { $0.label }

You can use reflection (Mirror) for this. I created this a while ago, might be helpful:

protocol DictionaryRepresentable {
  func dictionary() -> [String: Any]
}

extension DictionaryRepresentable {
  func dictionary() -> [String: Any] {
    let mirror = Mirror(reflecting: self)
    
    var dict: [String: Any] = [:]
    
    for (_, child) in mirror.children.enumerated() {
      if let label = child.label {
        dict[label] = child.value
      }
    }
    
    return dict
  }
}

class Foo: DictionaryRepresentable {
  private let baz: Int = 10
  
  func printMembers() {
    print(dictionary())
  }
}

let fooInstance = Foo()
fooInstance.printMembers() // ["baz": 10]

There’s no particularly good way to do this.

Take a step backwards for a moment. Why do you want to do this? What is the broader goal you’re trying to achieve?

5 Likes