Skip to content
Learn Netverks

Lesson

Step 19/36 53% through track

classes-swift

Classes

Last reviewed May 28, 2026 Content v20260528
Track mode
server_compiled
Means
Compiled runner
Reading
~1 min
Level
beginner

This lesson

This lesson teaches Classes: the syntax, patterns, and safety habits you need before advancing in Swift.

Structs are value types by default—know when classes and reference semantics are required.

You will apply Classes in contexts like: iPhone/iPad/Mac apps, server-side Swift (niche), and Apple toolchain projects.

Write Swift in main.swift with print(), click Run on server—the dev runner swiftc compiles and runs the binary (requires Swift toolchain, typically macOS; LEARNING_RUNNER_ENABLED=true).

When you can explain the previous lesson's ideas without copying starter code.

Classes provide reference semantics, inheritance, and deinitializers—use when instances must share identity (view controllers, network clients) or you need subclassing.

Class basics

class Counter {
    var count = 0
    func increment() { count += 1 }
}

let a = Counter()
let b = a
b.increment()
print(a.count)  // 1 — shared instance

Inheritance

class Animal {
    func speak() { print("...") }
}
class Dog: Animal {
    override func speak() { print("woof") }
}

Swift classes support single inheritance; protocols fill multiple-behavior needs.

Important interview questions and answers

  1. Q: When use class over struct?
    A: Shared mutable state, Objective-C interop, inheritance, or ARC-managed resources tied to instance lifetime.
  2. Q: final keyword?
    A: Prevents subclassing or overriding—default for performance and API stability in many frameworks.

Self-check

  1. Do two variables referencing one class instance share mutations?
  2. How many superclasses can a Swift class have?

Tip: Use classes when instances must share identity—view controllers, delegates, network clients.

Interview prep

When use class?

Shared identity, inheritance, Objective-C interop, or ARC-managed resources.

Inheritance limit?

Single superclass—protocols for multiple behaviors.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Playground

Runs on the configured server runner (dev: npm run runner with LEARNING_RUNNER_ENABLED=true). Output appears below the editor.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • final when?
  • Inheritance limits?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump