[swift-users] Implicitly capture a mutating self

Joe Groff jgroff at apple.com
Fri Dec 16 18:48:52 CST 2016


> On Dec 16, 2016, at 3:54 PM, Richard Wei <rxrwei at gmail.com> wrote:
> 
> Thanks. That’s true, but there are cases (like making BLAS calls) where I have to nest more than 4 `withUnsafeMutable…` closures. It’s safe by really clumsy. I just wish there were a cleaner way that looks like the do-notation in Haskell or for-notation in Scala.

It can help to define a pointer-taking function at the outer level of the scope where you need the pointers, so that instead of:

withUnsafeMutablePointer(&a) { p in
  withUnsafeMutablePointer(&b) { q in
    withUnsafeMutablePointer(&c) { r in
      doThing(p, q, r)
    }
  }
}

You could write:

func doThingWithPointers(_ p: UnsafeMutablePointer<A>, _ q: UnsafeMutablePointer<B>, _ r: UnsafeMutablePointer<C>) {
  doThing(p, q, r)
}

doThingWithPointers(&a, &b, &c)

-Joe


More information about the swift-users mailing list