Skip to content

Crash during optional key path access #70611

Open
@stephencelis

Description

@stephencelis

Description

I have code that appends key paths that is crashing at runtime when passing the key path to a value's key path subscript.

Reproduction

struct Foo {
  var bar: Bar?
}
struct Bar {
  var baz: Int?
}
extension Optional {
  subscript(default default: Wrapped) -> Wrapped {
    self ?? `default`
  }
}

let foo = Foo()
let kp1 = \Foo.bar
let kp2 = kp1.appending(path: \.?.baz)
let kp3 = kp2.appending(path: \.[default: 5])
foo[keyPath: kp3]  // 💥

💥 Could not cast value of type 'Swift.Optional<()>' (0x1df122378) to 'Swift.Int' (0x1df11e138).

Stack dump

N/A

Expected behavior

I expect this code not to crash, and ideally return the default 5.

Environment

swift-driver version: 1.87.3 Apple Swift version 5.9.2 (swiftlang-5.9.2.2.56 clang-1500.1.0.2.5)
Target: arm64-apple-macosx14.0

Additional information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugA deviation from expected or documented behavior. Also: expected but undesirable behavior.crashBug: A crash, i.e., an abnormal termination of softwarekey pathsFeature: key paths (both native and Objective-C)standard libraryArea: Standard library umbrella

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions