This is the sixth day of my participation in the August More text Challenge. For details, see: August More Text Challenge

Then is a Swift framework that has very little code but I use a lot.

Then is written by Suyeol Jeon. As the author’s statusalways coding, his contributions on GitHub are in full bloom. As the author describes it: A lazy programmer 😴, Then really makes you “lazy”.

Then the framework

Then is a syntax-sugar for Swift initializers that simplifies the amount of code required to initialize (or modify properties).

The Then framework is very simple, with around 60 lines of code.

then()

The Then framework extends a Then () method to NSObject. Here’s an official example:

let label = UILabel().then {
    $0.textAlignment = .center
    $0.textColor = .black
    $0.text = "Hello, World!"
}
Copy the code

It is equivalent to:

let label: UILabel = {
    let label = UILabel()
    label.textAlignment = .center
    label.textColor = .black
    label.text = "Hello, World!"
    return label
}()
Copy the code

By comparing the two pieces of code, it is obvious that:

  1. We can eliminate naming a local variable. After initializing a concrete instance, directly inthenBlock.
  2. When retrieving by variable name, you can quickly skip the same section of code. For example, when we search with the keyword label, the first part of the code has two matches and the second part of the code has eight matches.
  3. With THEN, you can clearly put your changes to an instance in a block when you write your code, and you can easily read your code.

In addition, we can use Then () for custom classes and constructs by extending the Then protocol:

extension MyType: Then {}

let instance = MyType().then {
    $0.really = "awesome!"
}
Copy the code

Then also provides do() and with() methods.

do()

UserDefaults.standard.do {
    $0.set("devxoul", forKey: "username")
    $0.set("[email protected]", forKey: "email")
    $0.synchronize()
}
Copy the code

Do () reduces the amount of code you type. The difference between do() and THEN () is that do() does not return a value, and then() returns self.

You can imagine how many userdefaults.standard would appear in the above code if you didn’t have to do.

with()

let newFrame = oldFrame.with {
    $0.size.width = 200
    $0.size.height = 100
}
newFrame.width // 200
newFrame.height // 100
Copy the code

With () modifies the new value to create a new value.

conclusion

The Then framework provides a total of three methods to reduce the amount of code:

  • then()Used when initializing entities (with return value)
  • do()Used to set properties (no return value)
  • with()For aValue form, modify the properties of the new instance, and return the modified instance.