To see the intermediate results in a chain sequence (method chaining, fluent pattern) without breaking the chain I created the following extension:
extension Loggable {
@discardableResult func log() -> Self {
log(nil)
}
@discardableResult func log(_ title: String?) -> Self {
if let title = title {
print(title, " ", self)
} else {
print(self)
}
return self
}
}
// MARK: also this
extension Int: Loggable {}
extension String: Loggable {}
extension Foo: Loggable {}
// and so on
so now I can write:
let x = foo
.bar(...)
.map { ... }
.log("intermediate result")
.baz
.filter {...}
.log()
.qux
.sort {...}
Which is good on the use site but I am not totally happy with the implementation side, specifically marking types Loggable.
Given there is no way to extend Any
, is the above "log" the best I can do in current Swift?
Edited example and included a wiki link to "method chaining".