Swift Raw Identifiers

Swift 6.2 adds raw identifiers to the language. Let’s see where that might be useful.

Raw Identifiers

Swift constant and variable identifier names cannot contain certain characters such as whitespace or mathematical symbols. They also cannot begin with a number. Swift 6.2 implements SE-0451 which allows us to relax those rules by surrounding the identifier name with backticks. There’s a couple of cases where I might find that useful:

Swift Testing Function Names

In Swift Testing, I like to write longer descriptions for tests. For example:

@Test("detail button tapped when no item selected")
func detailButtonTappedNoSelection() {
  ...
}

The downside is that you end up writing the description twice. Once for the actual description which shows up in the Test Navigator and again for the test function name. Using a raw identifier for the function name removes the duplication:

@Test
func `detail button tapped when no item selected`() {
  ...
}

Without the test description, the function name becomes the descriptive name and shows up in the Test Navigator, test reports, etc.

Note: It’s an error to have both an implicit and actual display name. Xcode offers a fix-it to remove one or the other.

Swift Enum Cases

One other situation where raw identifiers can be useful is with enum cases where you would normally want to use a number. For example, I have an enum for common video frame rates:

enum FrameRate {
  case frame24
  case frame25
  case frame2997
  case frame30
  ...
}

Swift doesn’t allow identifiers to start with a number so I ended up prefixing the frame rates with “frame”. Using raw identifiers I can write:

enum FrameRate {
  case `24`
  case `25`
  case `2997`
  case `30`
  ...
}

let timecode = Timecode(frameCount: 10, frameRate: .`24`)

I find it a little clumsy having to use backticks but I think it’s an improvement.

Learn More