Modifiable: Modify and Assign without Temporary Variables
This Protocol & Extension allow you to assign and modify all in one line.
I've been meaning to write this for a long time. It's working in Swift 4.1. It's definitely a tiny bit tricky, definitely not necessary, and perhaps too cute to be worth it. But it is cute!
import UIKit
/// Modifiable, Dan Rosenstark 2018, inspired from:
/// https://medium.com/@victor.pavlychko/using-self-in-swift-class-extensions-6421dab02587
protocol Modifiable {}
extension NSObject: Modifiable {}
extension Modifiable {
func modify(block: (Self)->()) -> Self {
block(self)
return self
}
}
/// examples
let view = UIView().modify { $0.backgroundColor = .green }
print(view.backgroundColor == UIColor.green)