Skip to content

Instantly share code, notes, and snippets.

@IanKeen
Created November 17, 2016 18:27
Show Gist options
  • Save IanKeen/5a9d3e67b450d2d88835c24705fc3f36 to your computer and use it in GitHub Desktop.
Save IanKeen/5a9d3e67b450d2d88835c24705fc3f36 to your computer and use it in GitHub Desktop.
NSDictionaryOfVariableBindings in Swift using Mirror 😁
extension Dictionary {
/**
Create a `Dictionary<Key, Pair>` from the provided `Sequence` of tuples
- parameter pairs: The `Sequence` of tuples used to create the `Dictionary<Key, Pair>`
*/
init(pairs: [(Key, Value)]) {
var result = Dictionary<Key, Value>(minimumCapacity: pairs.count)
for (key, value) in pairs {
result[key] = value
}
self = result
}
}
extension UIView {
private typealias BindingPair = (key: String, value: UIView)
/**
Performs the same function as `NSDictionaryOfVariableBindings` (which is not available in Swift)
*/
func viewBindings() -> [String: UIView] {
let mirror = Mirror(reflecting: self)
let pairs: [BindingPair] = mirror.children.flatMap { child in
guard
let label = child.label,
let view = child.value as? UIView
else { return nil }
return (label, view)
}
return Dictionary<String, UIView>(pairs: pairs)
}
}
class MyViewController: UIViewController {
private var label: UILabel = { ... }
private var textField: UITextField = { ... }
private var button: UIButton = { ... }
override func updateConstraints() {
let bindings = self.viewBindings()
/*
bindings = [
"label": self.label,
"textField": self.textField,
"button": self.button,
]
*/
// apply constraints...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment