Skip to content

[cxx-interop] An std::optional<bool>'s .value is always false in Release mode #84848

@mrousavy

Description

@mrousavy

Description

When passing an std::optional<bool> to Swift, it automatically conforms to the CxxOptional protocol. This protocol has a hasValue and a value properties:

Image

While hasValue seems to always hold the correct value (true), the value property only properly works in Debug mode. Once you build the app in Release mode, it always holds false instead of true for my boolean.

I confirmed this by

  1. Logging the boolean in C++ first, then in Swift, and it in C++ it was true whereas in Swift it was false
  2. Creating a helper function in C++ to actually get the value, then calling it from Swift - in which case it returned true again and works

Reproduction

Swift:

func myMethod(opt: helpers.specialized_std_optional_bool) {
  let wrongValue = opt.value
  let actualValue: Bool? = opt.hasValue ? helpers.get_std_optional_bool(opt) : nil
}

C++:

using specialized_std_optional_bool = std::optional<bool>;
bool get_std_optional_bool(std::optional<bool> opt) {
  return opt.value();
}

Expected behavior

I expect the .value property to always hold a correct value

Environment

swift-driver version: 1.127.14.1 Apple Swift version 6.2 (swiftlang-6.2.0.19.9 clang-1700.3.19.1)
Target: arm64-apple-macosx26.0

Additional information

Original bug reported in mrousavy/nitro#876

Metadata

Metadata

Assignees

Labels

bugA deviation from expected or documented behavior. Also: expected but undesirable behavior.c++ interopFeature: Interoperability with C++

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions