Skip to content

[SR-1528] Swift compiler requires closures without parameter lists to reference all arguments #44137

@swift-ci

Description

@swift-ci
Previous ID SR-1528
Radar rdar://problem/13254540
Original Reporter erica (JIRA User)
Type Bug
Environment

Swift 2.2

Additional Detail from JIRA
Votes 10
Component/s Compiler
Labels Bug
Assignee None
Priority Medium

md5: 2ed8141c3cd057578dc20e6b58317765

is duplicated by:

  • SR-5695 Error defining closure with more than 3 parameters
  • SR-6612 Contextual closure type expects N arguments, but <N was used in closure body.

relates to:

  • SR-3639 Surprising meaning of anonymous closure parameters if not all are used
  • SR-11389 Confusing error message when missing an overload

Issue Description:

Swift closures that do not explicitly declare an internal parameter list must reference all arguments using implicit $n shorthand names. If they do not, Swift complains that the contextual type for the closure argument "expects n arguments, which cannot be implicitly ignored." This requirement diminishes the efficacy of Swift's $n syntactic sugar. Eliminating the requirement means:

  • {} becomes a valid 'noop' closure in any context requiring a Void-returning closure.

  • Implementations can discard unnecessary code cruft and streamline their minimum implementation from { _(, _)* in } to {}.

  • { expression } becomes a valid closure in any context requiring a return value. The expression can offer a simple expression or literal, such as { 42 }.

  • The closure can mention some of its parameters without having to mention all of its parameters.

All the following closures should be valid and compile without error or warning:

{{let _: () -> Void = {}
let _: (Int) -> Void = {}
let _: (Int, Int) -> Int = { 5 }
let _: (Int, Int) -> Int = { $0 }
let _: (Int, Int) -> Int = { $1 }

doThing(withCompletion: {})
let x: (T) -> Void = {}}}

Chris L writes: "I consider this to be an obvious bug in the compiler. I don’t think it requires a proposal. Unfortunately it is non-trivial to fix…"

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugA deviation from expected or documented behavior. Also: expected but undesirable behavior.compilerThe Swift compiler itself

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions