Swift Configuration and “then”
I toyed around with a few ways to fix this issue, including making the instance variables optional and filling in the defaults at the usage site, but that ended up being just as clunky as the big initializer. What I settled on was: instead of making the variables optional, I made them mutable. That solves quite a few problems.
[…]
The
then
extension is a really useful library to have in your app. […] Since everything in Cocoa Touch inherits fromNSObject
, you can now use this function to configure lots of types, and you can do so at the declaration of the property. Swift will let you initialize things in-line (as long as they’re effectively a one line expression) […]
1 Comment RSS · Twitter
I'm doing the same but using a global function instead of an extension:
func with(_ object: T, update: @noescape (inout T) throws -> (Void)) rethrows -> T { var obj = object try update(&obj) return obj }
So, I don't have to add the protocol to all the Type I'm using just to be able to use it.
You can use it like that:
with(UILabel()) { // your init code. }