CIS 1951
Fall 2024

Swift Style Guide

Please stick to this style when writing code for this class; it's also recommended to follow these same guidelines outside the classroom! TLDR, always write clean, readable code.

Make it readable plz :sob:

Also reference the Swift API Design Guidelines or this guide for more information.

Naming Conventions

Syntax

  • Classes & Interfaces → UpperCamelCase. e.g. SchoolSchedule
  • Methods (functions) → lowerCamelCase. e.g. dropClass()
  • Variables → lowerCamelCase. e.g. let studentName = "Anthony" or var studentName = "Anthony"

Semantics

  • Variable names → should be a good representative of their use. Never use one-letter names (except for loop counters).

    // BAD
    let x = 5
    classMember.examScore = x
    
    // GOOD
    let score = 5
    classMember.examScore = score
    

Readability

  • Line Length → lines are at most 100 characters long (Xcode should take care of the formatting for you for the most part).

  • Vertical Spacing → add a blank line between methods for clarity.

  • Modifiers → include modifiers on seperate lines like below:

    struct ContentView: View {
        var body: some View {
            VStack {
                Text("Hello, world!")
                    .padding()  // its own line
                    .background(Color.red)  // its own line
                Button(action: {
                    print("Button tapped")
                }) {
                    Text("Tap me!")
                }
            }
        }
    }
    

Comments

Add clear comments when needed and when necessary.

  • If code can be understood in a glance, don't add a comment.
  • If code is complex, add a comment explaining what it does.

Curly Braces & If Statements

  • All curly braces start on the same line as preceding code.

  • else statements start on the same line as preceding curly brace.

  • No parentheses around if or else conditions.

    // BAD
    func delete()
    {
        if (isDeleted)
        {
            // ...
        }
        else
        {
            // ...
        }
    }
    
    // GOOD
    func delete() {
        if isDeleted {
            // ...
        } else {
            // ...
        }
    }
    

Semicolons

  • Just don't use them. It will work if you have them, but there's no need. Please don't use them.

let vs. var

  • Only use var if you know the variable will change.
  • Rule of thumb: declare everything as let, switch to var if you needed to change it later.

Nullable Types

  • It is preferred to declare variables and funciton return types as nullable ? where a null value can take place.
  • Use ! as a last resort if and only if you are 100% sure the variable will be defined beforehand.

Authored by Jordan Hochman and Yuying Fan, @Jan 2024.

Credit to Ali Krema from CIS 1950-201 Spring 2023 for Style Guide format.

Dates and times are displayed in EST.