Skip to content

Instantly share code, notes, and snippets.

@justAnotherDev
Created January 31, 2016 09:47
Show Gist options
  • Save justAnotherDev/7d3f420c97ba87931cf0 to your computer and use it in GitHub Desktop.
Save justAnotherDev/7d3f420c97ba87931cf0 to your computer and use it in GitHub Desktop.
DictionaryOfInstanceVariables - Swift version of NSDictionaryOfVariableBindings
func DictionaryOfInstanceVariables(container:AnyObject, objects: String ...) -> [String:AnyObject] {
var views = [String:AnyObject]()
for objectName in objects {
guard let object = object_getIvar(container, class_getInstanceVariable(container.dynamicType, objectName)) else {
assertionFailure("\(objectName) is not an ivar of: \(container)");
continue
}
views[objectName] = object
}
return views
}
// Example Usage
import UIKit
class ViewController: UIViewController {
var childA: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = UIColor.redColor()
return view
}()
var childB: UIButton = {
let view = UIButton()
view.setTitle("asdf", forState: .Normal)
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = UIColor.blueColor()
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(childA)
self.view.addSubview(childB)
let views = DictionaryOfInstanceVariables(self, objects: "childC", "childB")
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[childA]|", options: [], metrics: nil, views: views))
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[childB]|", options: [], metrics: nil, views: views))
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[childA][childB(==childA)]|", options: [], metrics: nil, views: views))
}
}
@SergeyPetrachkov
Copy link

small note for swift 3.1

func DictionaryOfInstanceVariables(container:AnyObject, objects: String ...) -> [String:Any] {
var views = String:Any
for objectName in objects {
guard let object = object_getIvar(container, class_getInstanceVariable(type(of: container), objectName)) else {
assertionFailure("(objectName) is not an ivar of: (container)")
continue
}
views[objectName] = object
}
return views
}

AnyObject --> Any
container.dynamicType --> type(of: container)

Regards,

Sergey

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment