Swift Naming Conventions: camelCase, PascalCase, and Constants
Swift naming conventions help you write code that is easier to read, easier to maintain, and more consistent with the rest of the language. This article explains how Swift prefers names for types, variables, functions, properties, enum cases, and constants so your code looks idiomatic and professional.
Quick answer: Use camelCase for variables, functions, and properties; use PascalCase for types like struct, class, enum, and protocol; and use clear, meaningful names for constants declared with let.
Difficulty: Beginner
Helpful to know first: You'll understand this better if you know basic Swift syntax, how let and var work, and the difference between types and values.
1. What Is Swift Naming Conventions?
Swift naming conventions are the style rules developers follow when choosing names for code elements. Swift does not force most naming styles, but the language and its standard library strongly encourage specific patterns so code stays readable and predictable.
- camelCase starts with a lowercase letter and capitalizes later words, such as userName or calculateTotal.
- PascalCase capitalizes every word, including the first one, such as UserProfile or NetworkError.
- Constants declared with let should have descriptive names that communicate meaning, not just that they are fixed values.
- Swift prefers names that read naturally and avoid unnecessary abbreviations.
- Names should describe what something is or does, not how it is implemented.
In practice, naming conventions are part language style and part communication tool. Good names let other developers understand your code before they read the implementation.
2. Why Swift Naming Conventions Matter
Clear naming is one of the fastest ways to make Swift code easier to work with. A well-named variable or type can eliminate the need for comments, reduce mistakes, and make APIs feel more natural to use.
Swift also uses naming as part of its design philosophy. Many standard library APIs read like English sentences, which makes call sites easier to understand.
- Readable names reduce cognitive load during reviews and debugging.
- Consistent casing helps you instantly recognize whether something is a type, value, or function.
- Meaningful constant names make code safer because they explain the purpose of the value.
- Good names improve autocomplete results and searchability in large codebases.
Bad naming often becomes a hidden cost. A confusing name may compile perfectly but create repeated misunderstandings every time someone revisits the code.
3. Basic Syntax or Core Idea
Swift naming conventions are not special syntax, but they are essential style rules. The most common patterns are simple:
Variables and functions use camelCase
Use lowercase for the first word and capitalize each new word after that.
let userName = "Ava"
func printGreeting() {
print("Hello!")
}Here, userName and printGreeting follow the standard Swift style for values and functions.
Types use PascalCase
Type names begin with a capital letter and capitalize each word.
struct UserProfile {
let displayName: String
}This makes type names stand out from variable names at a glance.
Constants use clear descriptive names
Use let when a value does not need to change, and name it by purpose.
let maximumLoginAttempts = 3
let welcomeMessage = "Welcome back"The key idea is consistency: the name should match the role of the symbol in your code.
4. Step-by-Step Examples
The best way to learn Swift naming conventions is to see how they apply in real code. The examples below show the most common cases you will write every day.
Example 1: Naming a variable
A variable that stores a user's first name should be descriptive and lowercase at the start.
var firstName = "Mia"
print(firstName)This is preferred over short or unclear names like fn because it immediately tells you what the value contains.
Example 2: Naming a function
Function names should describe an action, usually with a verb.
func calculateTotalPrice(subtotal: Double, taxRate: Double) -> Double {
return subtotal + (subtotal * taxRate)
}The function name is explicit, and the parameters also use lowercase camelCase for consistency.
Example 3: Naming a type
Types should be written in PascalCase so they are easy to identify.
enum PaymentStatus {
case pending
case paid
case failed
}The type name PaymentStatus clearly represents a category, while the cases use lower camel case.
Example 4: Naming a constant
A constant should communicate meaning instead of just saying it cannot change.
let minutesPerHour = 60
let supportEmail = "[email protected]"These names are clear, stable, and easy to reuse in later code.
5. Practical Use Cases
Swift naming conventions show up in almost every file you write. They are especially important in codebases with many collaborators.
- Model types like UserAccount, InvoiceItem, and NetworkResponse.
- Stored properties like emailAddress, isEnabled, and itemCount.
- Utility functions like loadProfile(), formatDate(), and validatePassword().
- Constants like apiBaseURL, retryDelaySeconds, and defaultPageSize.
- Enum cases like .success, .offline, and .unknown.
These naming patterns also help with code completion. When names are consistent, the right symbol is easier to spot.
6. Common Mistakes
Most naming bugs in Swift are not compiler errors, but they still make code harder to read and maintain. The mistakes below are some of the most common ones.
Mistake 1: Using PascalCase for variables and functions
Beginners sometimes capitalize every word in a variable or function name because they assume all words should look like type names. In Swift, that makes the code look unusual and less idiomatic.
Problem: This code compiles, but the names break Swift's usual style and make values look like types.
let UserName = "Noah"
func PrintGreeting() {
print("Hello")
}Fix: Use lower camel case for values and functions.
let userName = "Noah"
func printGreeting() {
print("Hello")
}The corrected version matches Swift conventions and makes the symbol roles easier to recognize.
Mistake 2: Using unclear abbreviations
Short names may save typing, but they often cost more time later when you need to remember what they mean.
Problem: Names like usr and qty are compact but too vague in larger codebases.
let usr = "Ada"
let qty = 12Fix: Prefer names that spell out the meaning clearly.
let userName = "Ada"
let quantity = 12The corrected names are easier to scan, search, and understand without context.
Mistake 3: Naming constants like temporary values
Constants should sound stable and purposeful. Names that look like throwaway temporary values make code feel less intentional.
Problem: A constant named temp or value1 does not explain what the data is for.
let temp = 30
let value1 = "OK"Fix: Name the constant after its meaning in the program.
let defaultTemperature = 30
let statusMessage = "OK"Meaningful constant names make the code self-documenting and reduce the need for comments.
7. Best Practices
Good naming is not only about casing. It is also about consistency, clarity, and matching Swift's style and API design conventions.
Practice 1: Use nouns for data and verbs for actions
Variables and properties usually represent things, while functions usually perform actions.
let userAge = 18
func sendEmail() {
// send mail here
}This convention makes symbols easier to classify just by reading them.
Practice 2: Keep Boolean names readable as questions or states
Boolean values are easier to use when their names imply true or false clearly.
let isLoggedIn = true
let hasPermission = falseNames that begin with is, has, or can often read naturally in conditions.
Practice 3: Match the surrounding API style
Swift code often reads best when related names follow the same pattern.
let minimumPasswordLength = 8
let maximumPasswordLength = 64Paired names become easier to compare when they share structure and wording.
8. Limitations and Edge Cases
Swift naming rules are flexible, but there are a few situations where the conventions can feel less obvious.
- Type names should usually be PascalCase, but generic placeholders like Element or Key are still type names even when they are short.
- Enum cases use lower camel case, not PascalCase, even though the enum itself uses PascalCase.
- Imported APIs from Apple frameworks may not perfectly match Swift style, and you should usually preserve the official API name at the call site.
- Two words that begin with an acronym can be tricky; Swift style generally favors readable names like apiBaseURL over awkward all-caps variants inside the name.
- Property wrappers, closures, and local constants still follow the same general naming rules, even when the syntax around them looks different.
A useful rule is that the more public the code is, the more important consistent naming becomes. Internal helper names still matter, but public APIs carry the most long-term impact.
9. Practical Mini Project
Let's build a small Swift file that demonstrates naming conventions in a realistic way: a simple product model, a pricing function, and a formatted summary string.
struct Product {
let name: String
let basePrice: Double
}
func finalPrice(for product: Product, taxRate: Double) -> Double {
return product.basePrice + (product.basePrice * taxRate)
}
let featuredProduct = Product(name: "Notebook", basePrice: 12.50)
let taxRate = 0.08
let price = finalPrice(for: featuredProduct, taxRate: taxRate)
print("\(featuredProduct.name) costs \(price) after tax.")This example uses PascalCase for the type Product, camelCase for the function finalPrice, and clear lowercase names for values like featuredProduct and taxRate. The result is code that reads naturally and is easy to extend.
10. Key Points
- Use camelCase for variables, properties, and functions.
- Use PascalCase for types such as structs, classes, enums, and protocols.
- Use descriptive names for constants declared with let.
- Prefer meaningful words over abbreviations that save only a little typing.
- Choose names that communicate purpose, not implementation details.
11. Practice Exercise
Rewrite the following symbols so they follow Swift naming conventions:
- A type for storing book information
- A constant for the maximum number of retries
- A function that returns whether a user can edit a post
- A Boolean value that tracks whether the document is saved
Expected output: The names should use PascalCase for the type and lower camel case for the values and function.
Hint: Ask yourself whether each name describes a type, a value, or an action.
Solution:
struct BookInfo {
let title: String
let author: String
}
let maximumRetries = 3
func canEditPost(userRole: String) -> Bool {
return userRole == "editor"
}
let isDocumentSaved = trueThis solution follows Swift's naming style and makes each symbol's purpose obvious.
12. Final Summary
Swift naming conventions are a small part of the language, but they have a big effect on how readable and maintainable your code feels. Using camelCase for values and functions, PascalCase for types, and meaningful names for constants gives your code a clean, familiar Swift style.
Good names are not just cosmetic. They help readers understand intent, reduce confusion in reviews, and make APIs easier to use correctly. When you choose names carefully, your code becomes more self-explanatory and easier to evolve over time.
As a next step, practice renaming existing Swift code in a small project. Focus on making names more specific, more consistent, and more natural to read.