Cartography (Permalink)
If you follow the Apple developer community, you've probably heard of Swift by now, Apple's new programming language for iOS and OS X apps.
Some of Swift's features, such as operator overloading and implicit closures allow us to create powerful yet typesafe DSLs. For example, I recently released my first Swift open source library, Cartography, that makes use of both of these features.
Inspired by the awesome FLKAutoLayout, Cartography allows you to create Auto Layout constraints in a declarative fashion.
While NSLayoutConstraint
supports what they call a visual format string, its
syntax is not very intuitive. Additionally, since it is, well, a string, the
compiler can't assist you with validating your expression either. Compare this
example I adapted from Apple's documentation
NSArray *constraint = [NSLayoutConstraint
constraintsWithVisualFormat:@"[view1]-20-[view2]"
options:0
metrics:nil
views:NSDictionaryOfVariableBindings(view1, view2)];
[view2 addConstraint:constraint];
with the equivalent Cartography code:
layout(view1, view2) { view1, view2 in
view2.left == view1.right + 20
}
Fixed aspect ratios can't even be expressed using the visual format string, you would have to use the lower level +constraintWithItem:
attribute:
relatedBy:
toItem:
attribute:
multiplier:
constant:
.
With Cartography, they are concise and readable:
layout(imageView) { imageView in
imageView.width == 2 * imageView.height
}
I also managed to create new attributes to constraint multiple attributes at once:
layout(view) { view in
view.size <= view.superview!.size / 2
view.center == view.superview!.center
}
As usual, you can find Cartography on GitHub.
Posted in working-on