Closed JiriTrecak closed 8 years ago
@JiriTrecak, cool. How can we use it in real-world?
I mean, there is ton of stuff, but if you want one concrete example:
profilePicture.when(Model.currentUser.isLoggedIn) {
$0.image = UIImage("avatar")
}
I'm not sure. Why not use:
if Model.currentUser.isLoggedIn {
profilePicture.image = UIImage("avatar")
}
I think it's more clear.
You are definitely right, but your example uses only one assign, which makes even .then {} useless
profilePicture.when(Model.currentUser.isLoggedIn) {
$0.image = UIImage("avatar")
$0.backgroundColor = .clearColor
$0.layer.cornerRadius = 2.0
}
This is definitely consistent with your idea of the usage, and I am sure others can come with very clever uses of this (personally, I use .then in cells extensively - and this is where I'd like to have option like this).
Of course then()
can be used with existing objects (e.g. profilePicture
as you mentioned), but then()
was originally designed to provide a simple way to initialize properties.
Imagine that we have an UILabel as a property. We can define this label, an also able to create an instance of it. However, we have to initialize label's properties in another location: init()
.
class MyClass {
let label = UILabel() // define and create an instance at here, but...
init() {
// initialize properties at here (why?)
self.label.textColor = .blackColor()
self.label.text = "Hi"
}
}
then()
solves it by using closures.
class MyClass {
// define and create an instance, then initialize properties
let label = UILabel().then {
$0.textColor = .blackColor()
$0.text = "Hi"
}
}
This is why I asked you for a real-world example. I think when()
is out of then()
's philosophy and can be replaced with if
statement.
I propose we add one more function - when. This serves exactly the same purpose, but "then" is only executed when initial condition is met. This is extremely useful in a lot of cases, as it changes often used syntax
to
The only problem is that it does not fit with name of your repository :D but I think it is okay :)