Does this have a real world use?

I was in a playing around mood today and created this:

infix operator ..

extension Functor
{
  public static func ..(lhs: inout Self, rhs: @escaping ((inout Self) -> ()))
  {
    defer
    {
      lhs.closure = nil
    }
    
    lhs.closure = rhs
    
    lhs.closure!(&lhs)
  }
}


public struct Test : Functor
{
  var closure: ((inout Test) -> ())?
  
  let name: String = "Steve Jobs"
}

Test code:

  {
    var test = Test()
    
    test .. { print($0.name) }
    
    test .. { $0.name = "Tim Cook"; print($0.name) }
  }

So, we have an object which can be passed any closure that takes Self as in input parameter and that can both read and write to that object on which the closure has been called.

Of course, the functor signatures could be added to as and when required. The idea of dynamic getter and setter closures, possibly with side-effects, comes to mind.

It may be totally useless, or it may spark off something wonderful :yum:

Looks like a way to spell the with construct that's been discussed a bit:

I don't know what the deal with assigning to closure is about, and your example doesn't take advantage of it.

1 Like