Skip to content

Commit 00ea74d

Browse files
committed
Update discussion of macros as default values [SE-0422] (#328)
Fixes: rdar://133387175
2 parents f33f7a7 + d8a9c99 commit 00ea74d

File tree

1 file changed

+30
-5
lines changed

1 file changed

+30
-5
lines changed

TSPL.docc/ReferenceManual/Expressions.md

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1520,14 +1520,39 @@ Macro-expansion expressions have the following form:
15201520
A macro-expansion expression omits the parentheses after the macro's name
15211521
if the macro doesn't take any arguments.
15221522

1523-
A macro-expansion expression can't appear as the default value for a parameter,
1524-
except the [`file()`][] and [`line()`][] macros from the Swift standard library.
1523+
A macro-expansion expression can appear as the default value for a parameter.
15251524
When used as the default value of a function or method parameter,
1526-
these macros are evaluated using the source code location of the call site,
1525+
macros are evaluated using the source code location of the call site,
15271526
not the location where they appear in a function definition.
1527+
However, when a default value is a larger expression
1528+
that contains a macro in addition to other code,
1529+
those macros are evaluated where they appear in the function definition.
15281530

1529-
[`file()`]: https://developer.apple.com/documentation/swift/file()
1530-
[`line()`]: https://developer.apple.com/documentation/swift/line()
1531+
```
1532+
func f(a: Int = #line, b: Int = (#line), c: Int = 100 + #line) {
1533+
print(a, b, c)
1534+
}
1535+
f() // Prints "4 1 101"
1536+
```
1537+
1538+
In the function above,
1539+
the default value for `a` is a single macro expression,
1540+
so that macro is evaluated using the source code location
1541+
where `f(a:b:c:)` is called.
1542+
In contrast, the values for `b` and `c`
1543+
are expressions that contain a macro ---
1544+
the macros in those expressions are evaluated
1545+
using the source code location where `f(a:b:c:)` is defined.
1546+
1547+
When you use a macro as a default value,
1548+
it's type checked without expanding the macro,
1549+
to check the following requirements:
1550+
1551+
- The macro's access level
1552+
is the same as or less restrictive than the function that uses it.
1553+
- The macro either takes no arguments,
1554+
or its arguments are literals without string interpolation.
1555+
- The macro's return type matches the parameter's type.
15311556

15321557
You use macro expressions to call freestanding macros.
15331558
To call an attached macro,

0 commit comments

Comments
 (0)