Skip to content

callAsFunction is not executed when called as trailing closure after explicit .init #87121

@maximkrouk

Description

@maximkrouk

Description

If callAsFunction is called as trailing closure after explicit .init, it doesn't get executed

Reproduction

Note

This example also extends this issue #74853
To reproduce #74853 - uncomment initializers on lines 8-14

import Testing

@Suite
struct CallAsFunctionAfterImplicitInit {
	struct Example {
		var value: Int = 0

		// init() {
		// 	self.init(value: 0)
		// }
		//
		// init(value: Int) {
		// 	self.value = value
		// }

		func incremented() -> Self {
			.init(value: value + 1)
		}

		func callAsFunction(modify modified: (Self) -> Self) -> Self {
			modified(self)
		}
	}

	@Test
	func example() async throws {
		do { // base case
			let bug: Example = .init() { $0.incremented() }
			#expect(bug.value == 1) // ❌ Expectation failed: (bug.value → 0) == 1
		}

		do { // explicit type also fails
			let bug = Example.init() { $0.incremented() }
			#expect(bug.value == 1) // ❌ Expectation failed: (bug.value → 0) == 1
		}

		do { // using init with args also fails
			let bug: Example = .init(value: 1) { $0.incremented() }
			#expect(bug.value == 2) // ❌ Expectation failed: (bug.value → 1) == 2
		}

		// Workarounds

		do { // use explicit type on rhs
			let workaround = Example() { $0.incremented() }
			#expect(workaround.value == 1) // ✅
		}

		do { // use closure as argument
			let workaround: Example = .init()(modify: { $0.incremented() })
			#expect(workaround.value == 1) // ✅
		}

		do { // use `self` with trailing closure
			let workaround: Example = .init().self { $0.incremented() }
			#expect(workaround.value == 1) // ✅
		}

		do { // use explicit call with trailing closure
			let workaround: Example = .init().callAsFunction { $0.incremented() }
			#expect(workaround.value == 1) // ✅
		}
	}
}

Expected behavior

callAsFunction is executed when called as trailing closure after explicit .init

Environment

MacOS Tahoe 26.0.1
Xcode 26.0.1 (17A400)

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

More complex example of this bug can be reproduced using this package

Metadata

Metadata

Assignees

No one assigned

    Labels

    triage neededThis issue needs more specific labels

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions