Swift Keywords

Swift keywords are reserved words that have a defined meaning in the language grammar. They are used to declare values and types, control program flow, build expressions, describe types, match patterns, and enable compiler directives.

A reserved keyword normally cannot be used as an identifier such as a variable, constant, function, or type name. When interoperability or an external API requires a keyword as a name, Swift lets you escape it with backticks.

</>
Copy
let `class` = "Advanced"
print(`class`)

Swift also has context-sensitive keywords. These words act as keywords only in particular grammatical positions and can be identifiers elsewhere. The sections below group the main keywords by their role in Swift source code.

Swift Keywords Used in Declarations

Declaration keywords introduce constants, variables, functions, types, protocols, extensions, operators, and access levels.

Swift declaration keywordsSwift declaration keywordsSwift declaration keywordsSwift declaration keywords
associatedtypeborrowingclassconsuming
deinitenumextensionfileprivate
funcimportinitinout
internalletnonisolatedopen
operatorprecedencegroupprivateprotocol
publicrethrowsstaticstruct
subscripttypealiasvar

The following example uses several declaration keywords. struct declares a structure, let declares a constant property, var declares a variable property, and func declares a method.

</>
Copy
struct Counter {
    let step: Int
    private var value = 0

    mutating func increment() {
        value += step
    }
}

Swift Keywords Used in Statements

Statement keywords control branching, loops, error handling, deferred work, pattern matching, and function exits.

Swift statement keywordsSwift statement keywordsSwift statement keywordsSwift statement keywords
breakcasecatchcontinue
defaultdeferdoelse
fallthroughforguardif
inrepeatreturnswitch
throwwherewhile
</>
Copy
for number in 1...5 {
    if number == 3 {
        continue
    }

    print(number)
}

In this example, for and in form the loop, if tests a condition, and continue skips the remaining statements for the current iteration.

Swift Keywords Used in Expressions and Types

Expression and type keywords participate in casting, error propagation, concurrency, Boolean and nil literals, member access, and type references.

Swift expression and type keywordsSwift expression and type keywordsSwift expression and type keywordsSwift expression and type keywords
Anyasawaitcatch
falseisnilrethrows
selfSelfsuperthrow
throwstruetry
</>
Copy
func integerValue(from value: Any) -> Int? {
    if let number = value as? Int {
        return number
    }

    return nil
}

Here, Any accepts a value of any type, as? performs a conditional cast, if checks whether the cast succeeded, and nil represents the absence of a value.

Swift Wildcard Pattern Keyword

The underscore token, _, is the wildcard pattern keyword. It intentionally ignores a value or omits a name in a pattern or declaration context.

</>
Copy
let (_, score) = ("Asha", 92)
print(score)

for _ in 1...3 {
    print("Retry")
}

Swift Keywords Beginning with #

Keywords beginning with a number sign are used for conditional compilation, availability checks, compiler directives, selectors, key paths, and literal expressions.

Number-sign Swift keywordsNumber-sign Swift keywordsNumber-sign Swift keywords
#available#colorLiteral#else
#elseif#endif#fileLiteral
#if#imageLiteral#keyPath
#selector#sourceLocation#unavailable
</>
Copy
#if os(iOS)
import UIKit
#elseif os(macOS)
import AppKit
#endif

Source-location values such as #file, #fileID, #filePath, #function, #line, and #column are provided through standard-library macros in current Swift versions rather than being listed as reserved number-sign keywords.

Swift Keywords Reserved in Specific Contexts

Context-sensitive keywords have a special grammatical meaning only where Swift expects them. Outside those positions, many of them may be used as ordinary identifiers.

Context-sensitive Swift keywordsContext-sensitive Swift keywordsContext-sensitive Swift keywordsContext-sensitive Swift keywords
associativityasyncconveniencedidSet
dynamicfinalgetindirect
infixlazyleftmutating
nonenonmutatingoptionaloverride
packagepostfixprecedenceprefix
Protocolrequiredrightset
someTypeunownedweak
willSet
</>
Copy
final class Account {
    private(set) var balance = 0 {
        willSet {
            print("New balance: \(newValue)")
        }
        didSet {
            print("Previous balance: \(oldValue)")
        }
    }
}

In this example, final, private, set, willSet, and didSet have special meanings in their declaration contexts.

Swift Keywords, Identifiers, and Literals

Keywords, identifiers, and literals are different kinds of Swift tokens:

  • Keywords have predefined grammatical meanings, such as let, if, and struct.
  • Identifiers are programmer-defined names, such as totalPrice, Customer, or calculateTax().
  • Literals directly represent values, such as 42, 3.14, "Swift", true, and nil.

Swift permits many Unicode characters in identifiers, but identifiers cannot begin with a digit. Identifiers beginning with two underscores are reserved for the Swift compiler and standard library.

Using a Swift Keyword as an Identifier

Surround a reserved keyword with backticks when it must be used as an identifier. This feature is mainly useful when working with generated code, external data models, or APIs whose names cannot be changed.

</>
Copy
struct Course {
    let title: String
    let `repeat`: Bool
}

let course = Course(
    title: "Swift Basics",
    repeat: false
)

print(course.repeat)

The backticks are not part of the identifier itself. Prefer a clearer non-keyword name when you control the API.

Common Swift Keyword Mistakes

  • Using old keyword lists: Swift evolves, so lists containing obsolete items such as dynamicType or old underscore-style source-location names may no longer describe the current language.
  • Confusing contextual words with globally reserved words: A contextual keyword is special only in specific grammar positions.
  • Changing keyword capitalization: Swift is case-sensitive. For example, self and Self have different meanings.
  • Using a keyword as a name without backticks: Escape a reserved word as `keyword` when a keyword-based identifier is unavoidable.
  • Confusing attributes and keywords: Constructs beginning with @, such as @available and @MainActor, are attributes rather than ordinary keywords.

Swift Keywords Frequently Asked Questions

What is a keyword in Swift?

A Swift keyword is a token with a predefined role in the language grammar. Examples include let, var, func, if, return, and struct.

Can a Swift keyword be used as a variable name?

A reserved keyword cannot normally be used as a variable name. It can be used when enclosed in backticks, as in let `class` = "A", although a non-keyword name is usually clearer.

What is the difference between reserved and contextual Swift keywords?

A reserved keyword has a language-defined meaning across the grammar and generally requires backticks when used as an identifier. A contextual keyword has special meaning only in a particular syntactic context and can often be used as an identifier elsewhere.

Are true, false, and nil Swift keywords or literals?

true, false, and nil are reserved keywords used as literal expressions. They represent Boolean values and the absence of a value.

What is the difference between self and Self in Swift?

self refers to the current instance or value. Self refers to the current type in a type context. Swift is case-sensitive, so these keywords are not interchangeable.

Swift Keywords Editorial QA Checklist

  • Confirm that declaration, statement, expression, pattern, number-sign, and contextual keyword groups match the current Swift language reference.
  • Check that all Swift keywords use exact case, especially Any, Self, Type, and Protocol.
  • Verify that obsolete entries such as dynamicType, _FILE_, and _LINE_ are not presented as current keywords.
  • Compile the added Swift examples and confirm that HTML-escaped arrows appear as -> only in the WordPress source.
  • Confirm that the backtick example explains both when escaping is valid and why descriptive non-keyword names are preferred.

Swift Keywords Summary

Swift keywords define the structure of declarations, statements, expressions, types, patterns, and compiler directives. Reserved keywords generally cannot be identifiers unless escaped with backticks, while contextual keywords are reserved only in specific grammatical positions.

We shall go through these keywords in this series of Swift Tutorial and explain their use with examples where necessary.