Typed throws and do/catch unusable inside withUnsafeMutableBufferPointer closure in Embedded Swift

Greetings for all!

Environment:

  • Embedded Swift (ESP32-C6, ESP-IDF v5.5.2)
  • Swift 6.x

Description:
In Embedded Swift, neither typed throws nor do/catch work inside a
withUnsafeMutableBufferPointer closure. This makes proper error handling
impossible when passing Swift arrays to C functions — an extremely common
pattern in embedded systems.

Minimal reproduction:

  enum MyError: Error {
      case failed
  }
  func read(buffer: UnsafeMutablePointer<UInt8>, length: Int) throws(MyError) { }

  var buf: [UInt8] = [0, 0, 0]

  // ❌ Case 1: typed throws lost — 'any Error' not allowed in Embedded Swift
  buf.withUnsafeMutableBufferPointer { ptr in
      try read(buffer: ptr.baseAddress!, length: 3)
  }

  // ❌ Case 2: do/catch fails with same reason
  buf.withUnsafeMutableBufferPointer { ptr in
      do {
          try read(buffer: ptr.baseAddress!, length: 3)
      } catch let error as MyError {
          print(error)
      }
  }

  // ✅ Only workaround — silently discards all errors
  buf.withUnsafeMutableBufferPointer { ptr in
      try? read(buffer: ptr.baseAddress!, length: 3)
  }

Expected:
Case 1 — typed throws should propagate through the closure.
Case 2 — do/catch with concrete type should work inside closure.

Impact:
Forces use of try? everywhere, making error handling impossible
when bridging Swift arrays to C APIs in Embedded Swift.
This is a critical limitation for embedded systems development
where C interop with buffers is fundamental.

1 Like

These are limitations that typed throws have in general. Currently, you need to do something like this:

    try buf.withUnsafeMutableBufferPointer { (ptr: inout UnsafeMutableBufferPointer<UInt8>) throws(MyError) -> Void in
        try read(buffer: ptr.baseAddress!, length: 3)
    }

    buf.withUnsafeMutableBufferPointer { ptr in
        do throws(MyError) {
            try read(buffer: ptr.baseAddress!, length: 3)
        } catch {
            print(error)
        }
    }
4 Likes

like it!