Skip to content
Learn Netverks

Lesson

Step 18/36 50% through track

structs-swift

Structs

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

This lesson

This lesson teaches Structs: 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 Structs 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.

Structs are Swift’s preferred way to model most data—value semantics, automatic memberwise initializers, and copy-on-write performance. Unlike Java classes, structs are copied by assignment.

Defining and using structs

struct Point {
    var x: Double
    var y: Double

    func distance(from other: Point) -> Double {
        let dx = x - other.x
        let dy = y - other.y
        return (dx*dx + dy*dy).squareRoot()
    }
}

var a = Point(x: 0, y: 0)
var b = a
b.x = 3
print(a.x)  // still 0

Compared to Kotlin data classes

Kotlin data class on JVM is reference-typed; Swift structs are true value types—important for reasoning about mutation and threading.

Important interview questions and answers

  1. Q: Struct vs class?
    A: Structs are value types copied on assignment; classes are reference types with ARC—prefer structs for models unless you need inheritance or shared identity.
  2. Q: Can structs have methods?
    A: Yes—methods, computed properties, and protocol conformance are all supported.

Self-check

  1. What happens to a when you mutate copy b?
  2. When should you choose a class over a struct?

Tip: Default to structs for models—value semantics simplify reasoning vs reference types.

Interview prep

Struct vs class?

Struct value semantics copied on assignment; class reference semantics with ARC.

When prefer struct?

Default for models and value data—most Swift APIs start here.

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

  • Struct vs class when?
  • Memberwise init?

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