swiftlang / swift-book

The Swift Programming Language book
Apache License 2.0
1.76k stars 162 forks source link

Clarify Function Type Restriction on Argument Label #253

Open tadbyt opened 10 months ago

tadbyt commented 10 months ago

Location

https://docs.swift.org/swift-book/documentation/the-swift-programming-language/types#Function-Type

Description

The following is an excerpt from the Function Type subsection of the Types section:

Argument names in functions and methods aren’t part of the corresponding function type. For example:

func someFunction(left: Int, right: Int) {} func anotherFunction(left: Int, right: Int) {} func functionWithDifferentLabels(top: Int, bottom: Int) {}

var f = someFunction // The type of f is (Int, Int) -> Void, not (left: Int, right: Int) -> Void. f = anotherFunction // OK f = functionWithDifferentLabels // OK

func functionWithDifferentArgumentTypes(left: Int, right: String) {} f = functionWithDifferentArgumentTypes // Error

func functionWithDifferentNumberOfArguments(left: Int, right: Int, top: Int) {} f = functionWithDifferentNumberOfArguments // Error

Because argument labels aren’t part of a function’s type, you omit them when writing a function type.

var operation: (lhs: Int, rhs: Int) -> Int // Error var operation: ( lhs: Int, rhs: Int) -> Int // OK var operation: (Int, Int) -> Int // OK

The sentence between the examples is slightly misleading. The code may either provide neither an argument label or parameter name (last line of the second example) or provide the wildcard as the argument label with a parameter name (middle line of the second example).

Correction

Append a second sentence between the two examples to read:

Because argument labels aren’t part of a function’s type, you omit them when writing a function type. This can be done either by providing neither an argument label nor parameter name or by providing a wildcard argument label with a parameter name.