Swift Identifiers

Swift Introduction

🆔 Swift Identifiers (Names in Swift)

In Swift Identifiers is the name used to identify variables, constants, functions, classes, structs, enums, etc.

Simply put 👉 Identifiers are names given to program elements.


 What Are Identifiers Used For?

Identifiers name:

  • Variables

  • Constants

  • Functions

  • Classes / Structs / Enums

  • Protocols

  • Properties

Example:

var age = 25
let pi = 3.14
func calculateSum() { }

Here, age, pi, and calculateSum are identifiers.


 Rules for Swift Identifiers (Very Important ⚠️)

✅ Allowed

  1. Can start with:

    • A letter (a–z, A–Z)

    • An underscore (_)

  2. Can contain:

    • Letters

    • Numbers

    • Underscore _

  3. Unicode characters are allowed (but not recommended)

var name = "Swift"
var _count = 10
var user1 = "Amit"

❌ Not Allowed

  1. Cannot start with a number

  2. Cannot contain spaces

  3. Cannot use Swift keywords directly

var 1value = 10 // ❌
var user name = "" // ❌
var class = 5 // ❌ keyword

 Swift Is Case-Sensitive

var age = 20
var Age = 25

age and Age are different identifiers


 Using Keywords as Identifiers (Backticks Trick 🔥)

It allows keywords as identifiers using backticks.

var class = "Swift"
print(class)

✔ Works, but not recommended in real projects


Identifier Naming Conventions (Best Practices ✅)

 Camel Case (Recommended)

var studentName = "Sanjit"
func calculateTotalMarks() { }

 Pascal Case (Types Only)

struct StudentData { }
class UserProfile { }

 Avoid This ❌

var a = 10 // unclear
var x1y2z3 = 20 // confusing

 Valid vs Invalid Identifiers

Identifier Valid?
totalMarks
_tempValue
user123
123user
user-name
func

 Identifiers in Different Contexts

Variable

var score = 90

Constant

let maxLimit = 100

Function

func greetUser() {
print("Hello")
}

Class

class EmployeeDetails { }

🧠 Summary

  • Identifiers are names of program elements

  • Swift identifiers are case-sensitive

  • Must follow strict naming rules

  • Use camelCase for variables & functions

  • Avoid keywords and confusing names

You may also like...