Skip to content

Unexpected Behavior in Swift 5.9 with ~Copyable and consuming in For Loop #68230

Open
@ojun9

Description

@ojun9

Description

When using the ~Copyable and consuming features of Swift 5.9 within a for loop, the expected compile-time error is not produced.
Instead, the code executes and results in unexpected deinitialization behavior.

Steps to reproduce

Here's the code sample:

struct MyValue: ~Copyable {
    var value = 0

    init() { print("init:", value) }
    deinit { print("deinit:", value) }

    consuming func run() {
        return
    }
}

func main() {
    var myValue = MyValue()

    for tmp in 1 ... 3 {
        myValue.value = tmp
        myValue.run()
    }
}
main()

Output:

init: 0
deinit: 1
deinit: 2
deinit: 3
deinit: 3

Expected behavior

When using ~Copyable and consuming within a for loop, the compiler should generate a compile-time error.
This error is not produced, leading to unnecessary calls to deinit. The lack of a compile-time error could lead to incorrect object creation and destruction.

Environment

  • Swift compiler version info: Apple Swift version 5.9 (swiftlang-5.9.0.128.106 clang-1500.0.40.1)
  • Xcode version info: Xcode 15.0 Build version 15A5229m (beta 8)
  • Deployment target: Any

Additional information

  1. Adding a member variable like the following to the struct causes a runtime error.
var id = UUID().uuidString
  1. I have also disassembled the main() and run() functions and verified that deinit is being called in both functions.

Metadata

Metadata

Assignees

No one assigned

    Labels

    accepts invalidBug: Accepts invalidbugA deviation from expected or documented behavior. Also: expected but undesirable behavior.for-in loopsFeature: for-in loopsnoncopyable struct/enumFeature → declarations: Noncopyable value type declarationsstructFeature → type declarations: Structure declarationsswift 5.9

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions