Created
November 17, 2016 18:27
-
-
Save IanKeen/5a9d3e67b450d2d88835c24705fc3f36 to your computer and use it in GitHub Desktop.
NSDictionaryOfVariableBindings in Swift using Mirror π
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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