Swift Naming Conventions 🎯

beginner
7 min

Swift Naming Conventions 🎯

Welcome to the Swift Naming Conventions tutorial! In this lesson, we'll explore the essential guidelines for naming variables, constants, functions, types, and more. Let's dive in!

Naming Variables and Constants 📝

In Swift, variable and constant names follow the same rules. Here's a simple rule to remember:

  1. Start with a lowercase letter (a-z or _)
  2. Followed by any combination of lowercase letters (a-z), digits (0-9), or underscores (_)
  3. Can't start with a digit
  4. Keywords, reserved words, and special characters are off-limits

Examples:

swift
let name: String = "John Doe"let 99Bottles: Int = 99 let _mySecretVariable: Int = 42 let myVariable99: Int = 99

Naming Functions 💡

Function names in Swift follow similar naming rules:

  1. Start with a lowercase letter (a-z or _)
  2. Followed by any combination of lowercase letters (a-z), digits (0-9), or underscores (_)
  3. Can't start with a digit
  4. Use verbs, nouns, or a combination to describe what the function does
  5. Use camelCase notation (e.g., calculateTotalCost, getUserName)

Examples:

swift
func calculateTotalCost(items: [Item], taxRate: Double) -> Double { // Function body } func getUserName(user: User) -> String { // Function body }

Naming Types 📝

When naming Swift types like classes, structures, enumerations, and protocols, follow these rules:

  1. Start with an uppercase letter (A-Z)
  2. Followed by any combination of uppercase letters (A-Z), lowercase letters (a-z), digits (0-9), or underscores (_)
  3. Use nouns or noun phrases to describe the type
  4. Use PascalCase notation (e.g., User, Item, Shape)

Examples:

swift
struct Item { // Type definition } protocol Networkable { // Protocol definition } class User { // Class definition }

CamelCase vs. PascalCase

CamelCase is used for naming functions and variables, while PascalCase is used for naming types in Swift.

Quiz 💡

Question: What's the correct way to name a variable in Swift?

A: 99 B: myVariable99 C: _mySecretVariable

Correct: B Explanation: Variable names should start with a lowercase letter and can use underscores, but not digits at the beginning.


Mastering naming conventions is a crucial step in becoming a proficient Swift programmer. By following these guidelines, you'll create code that's easy to read and maintain. Happy coding! 🚀