我可以在 Swift 中的变量名或枚举符号的开头使用 $ 吗?

Can I use $ at beginning of variable name or enum symbol in Swift?

如题。例如:

enum MyEnum {
  case $SYMBOL
}

let $foo = MyEnum.$SYMBOL

我得到 error: expected numeric value following '$'.

有趣的是,$可以用在变量名的中间。是否有我们可以在开始时使用的符号列表?

理由:

根据 Apple 的语言指南 (link):

Constant and variable names cannot contain whitespace characters, mathematical symbols, arrows, private-use (or invalid) Unicode code points, or line- and box-drawing characters. Nor can they begin with a number, although numbers may be included elsewhere within the name.

不禁止美元符号。

但是,Closure 部分确实提到使用 [=12=]</code> 作为 Shorthand 参数名称:</p> <blockquote> <p>Swift automatically provides shorthand argument names to inline closures, which can be used to refer to the values of the closure’s arguments by the names [=16=], , , and so on.</p> </blockquote> <p>开头保留美元符号的使用。这与之前的规则相矛盾。</p> <p> Xcode 游乐场使情况进一步复杂化。如果我创建一个 Swift playground 文件并粘贴我的代码,该变量将被评估为 <code>(Enum Value).

Can I use $ at beginning of variable name or enum symbol in Swift?

否。 如果您查看 "Grammar of an Identifier," 下的 Lexical Structure 部分,您会看到一个列表,其中列出了所有允许的字符范围identifier_head$U+0024 未包含在列表中。

如果你再深入一点,你会发现 enum-case-name 是一个 identifier 和一个 variable-name 也是一个 identifier,因此标识符的语法决定了允许的内容。

Dollar sign is not forbidden.

您链接的部分中的 "forbidden" 个字符列表似乎并不详尽。不难想出一些没有在语法中列出但没有在语法中列出的字符:@#?...

Can you explain why my code does not fail in playground? Does playground get special treatment?

这可能是一个错误 -- 只是 playground 稍微宽松一些的情况。