swiftswift-playground

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


As title. For example:

enum MyEnum {
  case $SYMBOL
}

let $foo = MyEnum.$SYMBOL

I get error: expected numeric value following '$'.

Interestingly, $ can be used in middle of variable name. Is there a list of symbols we can use at beginning?

Justification:

According to Apple's language guide (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.

Dollar sign is not forbidden.

However, the Closure section does mention the use of $0, $1 as Shorthand Argument Names:

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 $0, $1, $2, and so on.

which reserves the use of dollar sign at beginning. This contradicts the previous rule.

The Xcode Playground further complicate the situation. If I create a Swift playground file and paste my code, the variable will be evaluated as a (Enum Value).


Solution

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

    No. If you look at the Lexical Structure section under "Grammar of an Identifier," you'll see a list of all the ranges of characters that are allowed as identifier_head. $, or U+0024, is not included in the list.

    If you dig a little further, you'll find that an enum-case-name is an identifier and a variable-name is also an identifier, so the grammar for identifiers governs what's allowed.

    Dollar sign is not forbidden.

    It seems that the list of "forbidden" characters in the section you linked is not exhaustive. It's not hard to come up with a number of characters not listed there that are nevertheless not listed in the grammar: @, #, ?...

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

    It's probably a bug -- just a case where the playground is slightly more permissive.


    Update: This answer dates back to the early days of Swift. Nearly a decade later, a better answer is that $ at the beginning of an identifier has special meaning in at least two cases.