[swift-users] Chaining struct-mutating funcs

Dave Abrahams dabrahams at apple.com
Mon Aug 8 12:59:23 CDT 2016


on Fri Aug 05 2016, Joe Groff <swift-users-AT-swift.org> wrote:

> Since your backing buffer is copy-on-write, you can do the in-place
> mutation optimization in your immutable implementations, something
> like this:
>
> class C {
>   var value: Int
>   init(value: Int) { self.value = value }
> }
>
> struct S { var c: C }
>
> func addInts(x: S, y: S) -> S {
>   var tmp = x
>   // Don't use x after this point so that it gets forwarded into tmp
>   if isKnownUniquelyReferenced(&tmp.c) {
>     tmp.c.value += y.c.value
>     return tmp
>   } else {
>     return S(c: C(value: tmp.c.value + y.c.value))
>   }
> }
>
> which should let you get similar efficiency to the mutating
> formulation while using semantically immutable values.

Yep, that works.  The only other trick I know of is to create a
composition of operations that you apply at the end with an operator:

    pixelXes <- multiply(perspectiveCorrections).sin
    speeds <- multiply(pixelXes)
              .multiply(feetToMeters)
              .subtract(cameraSpeed.mean)
    let sumSquaredOfResiduals = speeds.sumOfSquares

HTH,

-- 
-Dave



More information about the swift-users mailing list