Chapter 13: Swift Identifiers
1. What is an identifier in Swift?
An identifier is simply the name you give to:
- variables (let / var)
- constants
- functions
- types (structs, classes, enums, protocols…)
- parameters
- properties
- labels
- etc.
Basically — almost everything you name yourself in code is an identifier.
Examples of identifiers:
|
0 1 2 3 4 5 6 7 8 9 |
let userName // identifier = userName var currentScore // identifier = currentScore func calculateTax() // identifier = calculateTax struct ShoppingCart // identifier = ShoppingCart |
2. Basic rules — what characters are allowed?
Swift has quite flexible but clear rules for identifiers.
Allowed characters:
- Letters (Unicode letters — very broad!)
- English: a–z, A–Z
- Accented letters: é, ñ, ç, ü, ā, ś, etc.
- Many other scripts: Devanagari, Bengali, Tamil, Arabic, Chinese, Japanese, Korean, etc.
- Digits0–9 → but cannot be the first character
- Underscore _
- Emoji (yes — really!)
- Combining characters (diacritics, etc.)
Not allowed:
- Spaces
- Most symbols: @, #, $, %, &, *, etc.
- Hyphen – (very common mistake coming from CSS/HTML)
- Starting with a digit
3. Real examples — valid and invalid identifiers
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
// Valid identifiers let userName let user_name let _privateCache let π // Greek pi — valid! let caféPrice let résumé // accented characters are fine let こんにちは // Japanese — completely valid let మంచి_పేరు // Telugu script — valid let 😺Count // emoji is allowed let count2 let maxLevelReached_ // Invalid identifiers let user-name // ❌ hyphen not allowed let 2ndPlace // ❌ cannot start with digit let user@name // ❌ @ not allowed let total% // ❌ % not allowed let class // ❌ 'class' is a keyword |
4. Keywords — names you cannot use
Swift has reserved keywords that you cannot use as identifiers (unless you escape them with backticks — more on that later).
Common keywords you’ll bump into:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
let let // ❌ cannot let var // ❌ let func // ❌ let if // ❌ let class // ❌ let struct // ❌ let enum // ❌ let protocol // ❌ let self // ❌ (most of the time) let true // ❌ let false // ❌ let nil // ❌ |
5. Using backticks to escape keywords (rare but useful)
You can use a keyword as an identifier by wrapping it in backticks
|
0 1 2 3 4 5 6 7 8 9 10 11 |
let `class` = "Economy" // valid — backticks escape the keyword let `self` = "important" // unusual but compiles func `repeat`(times: Int) { // ... } |
Realistic use cases (not very common but they exist):
- Interfacing with C/Objective-C APIs where a keyword is used
- Writing code generators
- Porting code from other languages
- Teaching/learning (to show escaping)
Most Swift developers try to avoid this — it’s better to rename the variable.
6. Naming conventions — what real Swift developers actually do
| Kind of identifier | Convention (2025–2026 style) | Examples |
|---|---|---|
| Variables & constants | camelCase | userName, currentTemperature, maxRetries |
| Types (struct, class, enum, protocol) | UpperCamelCase | UserProfile, NetworkManager, HTTPStatus |
| Functions & methods | camelCase | fetchUserData, calculateTotalPrice |
| Constants (especially global/static) | sometimes UPPER_CASE | API_KEY, MAX_UPLOAD_SIZE |
| Private properties | Often camelCase + private | private var internalCache |
| Parameters | camelCase | userID, newPassword |
| Associated values in enums | camelCase | case success(message: String) |
7. Very common beginner mistakes (and better alternatives)
| Mistake | Bad example | Better / correct style | Why better? |
|---|---|---|---|
| Using hyphens | max-size | maxSize | Hyphens not allowed |
| Starting with number | 2ndPlayer | secondPlayer or player2 | Rule violation |
| Using keyword without backticks | let class = "Premium" | let userClass = "Premium" or let class` = … | Avoids confusion & backticks |
| Very long unreadable names | thisIsTheCurrentUserSelectedProfilePictureUrl | profilePictureURL | Readability & maintainability |
| Inconsistent casing | User_name, userName, username | Pick one style (usually camelCase) | Team consistency & clarity |
| Overly short / cryptic names | x, tmp, a1 | index, temporaryValue, userAge | Future you will thank you |
8. Practical examples — clean, real-world naming
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
// Good naming in a small struct struct Product { let productID: String var name: String var price: Decimal var isAvailable: Bool private var stockQuantity: Int func discountPrice(percentage: Double) -> Decimal { price * (1 - Decimal(percentage / 100)) } } // Good naming in a function func fetchUserProfile( userID: UUID, completion: @escaping (Result<UserProfile, NetworkError>) -> Void ) { // ... } // Constants group enum AppConstants { static let maxUsernameLength = 30 static let defaultTimeoutSeconds: TimeInterval = 30 static let apiBaseURL = URL(string: "https://api.example.com")! } |
9. Quick reference – allowed vs not allowed
| Type of character | First character? | Later characters? | Example |
|---|---|---|---|
| English letter | Yes | Yes | userName |
| Digit | No | Yes | player2 |
| Underscore _ | Yes | Yes | _cache, max_count |
| Emoji | Yes | Yes | 😺Counter, 🚀Launch |
| Accented letter | Yes | Yes | caféPrice, straßeLength |
| Non-Latin script | Yes | Yes | नाम, 価格 |
| Hyphen – | No | No | ❌ max-size |
| Space | No | No | ❌ |
| Most symbols (@#$%) | No | No | ❌ |
Would you like to go deeper into any of these next?
- Naming conventions in more detail (SwiftUI vs backend vs UIKit)
- When and why to use backticks
- How to name variables vs functions vs types
- Common anti-patterns in naming
- Or move to another topic (variables, constants, printing, optionals…)
Just tell me what feels most useful right now — we’ll keep the same detailed, teacher-like style 😊
