A Box that provides extensions which can be method-chain.

Updated
Dec 27, 2020 7:53 PM
Created
Dec 27, 2020 7:52 PM
Tags
Swift
Keywords
let result = ""^.map { Int($0) }.do { print($0 as Any) }^

let view = UIView()^.do {
  $0.backgroundColor = .white
}^

postfix operator ^

postfix func ^ <T>(argument: T) -> Chain<T> {
  .init(argument)
}

postfix func ^ <T>(argument: Chain<T>) -> T {
  argument.value
}

public struct Chain<Value> {

  public let value: Value

  public init(_ value: Value) {
    self.value = value
  }

  public func map<U>(_ transform: (Value) throws -> U) rethrows -> Chain<U> {
    .init(try transform(value))
  }

  public func `do`(_ applier: (Value) throws -> Void) rethrows -> Chain<Value> {
    try applier(value)
    return self
  }

}