
Swift: Lazy Properties in Structs - ingve
http://oleb.net/blog/2015/12/lazy-properties-in-structs-swift/
======
kazinator
I put this into TXR Lisp a few weeks ago. Well, not exactly _this_. Rather,
quite simply, _any struct_ can be lazily instantiated with the lnew operator.
This gives you the object instance with its identity, but not yet initialized.
When you touch it, then all of it materializes. (It's not a per-slot behavior,
in other words.)

The commit for this could almost fit on a napkin:
[http://www.kylheku.com/cgit/txr/commit/?id=eb483eb39fa4570d1...](http://www.kylheku.com/cgit/txr/commit/?id=eb483eb39fa4570d1178a3f71fb65be908fd0d01)

Circular example: two structs are constructed so they refer to each other, in
a single step, by using mlet for the mutual scoping, and lnew for the
construction semantics:

    
    
      1> (defstruct node nil left right value)
      #<struct-type node>
      2> (defvar circ (mlet ((a (lnew node left b value 0))
                             (b (lnew node right a value 1)))
                        a))
      circ
      3> circ.value
      0
      4> circ.left.value
      1
      5> circ.left.right.value
      0
    

Lazy infinite chain of nodes, each containing a higher count value than its
predecessor:

    
    
      1> (defstruct node () next count)
      #<struct-type node>
      2> (defun count-chain (init)
           (lnew node count init next (count-chain (succ init))))
      count-chain
      3> (defvarl x (count-chain 0))
      x
      4> x.count
      0
      5> x.next.count
      1
      6> x.next.next.count
      2
      7> x.next.next.next.count
      3
      8> x.next.next.next.next.count
      4
      9> x.count
      0
      10> x.next.count
      1

------
melling
I just started using structs in Swift within the past couple of weeks.

There's actually a lot written on the topic:

[http://www.h4labs.com/dev/ios/swift.html?age=10000&q=structs](http://www.h4labs.com/dev/ios/swift.html?age=10000&q=structs)

