Lexing an Input String

The first phase of your expression-evaluating compiler is lexing. In computer science, lexing is the process of turning some input into a sequence of tokens. A token is something with meaning, like a number or a plus sign (the two tokens your compiler will recognize). Lexing is sometimes referred to as “tokenizing” because you are turning some input that is meaningless to the compiler (like a string) into a sequence of meaningful tokens.

Create a new macOS playground named ErrorHandling. Define an enumeration that has cases for the two kinds of token.

Example 23.1. Declaring the Token type
import Cocoa

var str = "Hello, playground"

enum Token {
    case number(Int)
    case plus
}

When building something like a lexer, logging ...

Get Swift Programming: The Big Nerd Ranch Guide, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.