Skip to content

[Stdlib] Fix swift_setAtWritableKeyPath to check for ReferenceWritableKeyPaths. #34729

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions stdlib/public/core/KeyPath.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1920,6 +1920,12 @@ func _setAtWritableKeyPath<Root, Value>(
keyPath: WritableKeyPath<Root, Value>,
value: __owned Value
) {
if type(of: keyPath).kind == .reference {
return _setAtReferenceWritableKeyPath(root: root,
keyPath: _unsafeUncheckedDowncast(keyPath,
to: ReferenceWritableKeyPath<Root, Value>.self),
value: value)
}
// TODO: we should be able to do this more efficiently than projecting.
let (addr, owner) = keyPath._projectMutableAddress(from: &root)
addr.pointee = value
Expand Down
15 changes: 15 additions & 0 deletions test/stdlib/KeyPath.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1028,5 +1028,20 @@ keyPath.test("tail allocated c array") {
expectEqual(4, offset)
}

keyPath.test("ReferenceWritableKeyPath statically typed as WritableKeyPath") {
let inner = C<Int>(x: 42, y: nil, z: 43)
var outer = C<C<Int>>(x: 44, y: nil, z: inner)
let keyPath = \C<C<Int>>.z.x
let upcastKeyPath = keyPath as WritableKeyPath

expectEqual(outer[keyPath: keyPath], 42)
outer[keyPath: keyPath] = 43
expectEqual(outer[keyPath: keyPath], 43)

expectEqual(outer[keyPath: upcastKeyPath], 43)
outer[keyPath: upcastKeyPath] = 44
expectEqual(outer[keyPath: upcastKeyPath], 44)
}

runAllTests()