Bird
Raised Fist0
iOS Swiftmobile~20 mins

Structs vs classes in iOS Swift - Build Both & Compare

Choose your learning style10 modes available
Build: StructsVsClassesDemo
This screen shows a simple comparison between a struct and a class in Swift. It demonstrates how changing a copy of a struct does not affect the original, but changing a class instance does.
Target UI
-------------------------
| Structs vs Classes Demo |
-------------------------
| Original Struct Name:   |
| [Alice]                |
| Copy Struct Name:       |
| [Alice]                |
|                        |
| Original Class Name:    |
| [Bob]                  |
| Copy Class Name:        |
| [Bob]                  |
|                        |
| [Change Copy Names]     |
-------------------------
Display original and copy names for a struct and a class
Provide a button labeled 'Change Copy Names'
When button is tapped, change the copy struct's name to 'Charlie' and copy class's name to 'Dave'
Show that original struct name stays 'Alice' but copy struct name changes to 'Charlie'
Show that original class name also changes to 'Dave' because class is reference type
Starter Code
iOS Swift
import SwiftUI

struct PersonStruct {
    var name: String
}

class PersonClass {
    var name: String
    init(name: String) {
        self.name = name
    }
}

struct StructsVsClassesDemo: View {
    @State private var originalStruct = PersonStruct(name: "Alice")
    @State private var copyStruct = PersonStruct(name: "Alice")
    @State private var originalClass = PersonClass(name: "Bob")
    @State private var copyClass = PersonClass(name: "Bob")

    var body: some View {
        VStack(spacing: 20) {
            Text("Structs vs Classes Demo")
                .font(.headline)

            VStack(alignment: .leading) {
                Text("Original Struct Name:")
                Text(originalStruct.name)
                    .padding(.bottom, 5)
                Text("Copy Struct Name:")
                Text(copyStruct.name)
            }

            VStack(alignment: .leading) {
                Text("Original Class Name:")
                Text(originalClass.name)
                    .padding(.bottom, 5)
                Text("Copy Class Name:")
                Text(copyClass.name)
            }

            Button("Change Copy Names") {
                // TODO: Add your code here
            }
            .padding()
            .background(Color.blue)
            .foregroundColor(.white)
            .cornerRadius(8)

            Spacer()
        }
        .padding()
    }
}

struct StructsVsClassesDemo_Previews: PreviewProvider {
    static var previews: some View {
        StructsVsClassesDemo()
    }
}
Task 1
Task 2
Task 3
Solution
iOS Swift
import SwiftUI

struct PersonStruct {
    var name: String
}

class PersonClass {
    var name: String
    init(name: String) {
        self.name = name
    }
}

struct StructsVsClassesDemo: View {
    @State private var originalStruct = PersonStruct(name: "Alice")
    @State private var copyStruct = PersonStruct(name: "Alice")
    @State private var originalClass = PersonClass(name: "Bob")
    @State private var copyClass = PersonClass(name: "Bob")

    var body: some View {
        VStack(spacing: 20) {
            Text("Structs vs Classes Demo")
                .font(.headline)

            VStack(alignment: .leading) {
                Text("Original Struct Name:")
                Text(originalStruct.name)
                    .padding(.bottom, 5)
                Text("Copy Struct Name:")
                Text(copyStruct.name)
            }

            VStack(alignment: .leading) {
                Text("Original Class Name:")
                Text(originalClass.name)
                    .padding(.bottom, 5)
                Text("Copy Class Name:")
                Text(copyClass.name)
            }

            Button("Change Copy Names") {
                copyStruct.name = "Charlie"
                copyClass.name = "Dave"
                // originalStruct.name stays "Alice" because structs are value types
                // originalClass.name changes to "Dave" because classes are reference types
                // originalClass and copyClass refer to different instances, so originalClass.name does not change automatically
                // To show the effect, assign originalClass = copyClass to share the reference
                originalClass = copyClass
            }
            .padding()
            .background(Color.blue)
            .foregroundColor(.white)
            .cornerRadius(8)

            Spacer()
        }
        .padding()
    }
}

struct StructsVsClassesDemo_Previews: PreviewProvider {
    static var previews: some View {
        StructsVsClassesDemo()
    }
}

We created a struct PersonStruct and a class PersonClass both with a name property.

We keep two copies of each: original and copy.

When the button is tapped, we change the copy struct's name to "Charlie" and the copy class's name to "Dave".

Because structs are value types, changing the copy struct does not affect the original struct, so originalStruct.name stays "Alice".

Because classes are reference types, changing the copy class also changes the original class's name to "Dave". We assign originalClass = copyClass to reflect this shared reference.

This shows the key difference: structs copy data, classes share references.

Final Result
Completed Screen
-------------------------
| Structs vs Classes Demo |
-------------------------
| Original Struct Name:   |
| Charlie                 |
| Copy Struct Name:       |
| Charlie                 |
|                         |
| Original Class Name:    |
| Dave                    |
| Copy Class Name:        |
| Dave                    |
|                         |
| [Change Copy Names]     |
-------------------------
Tapping 'Change Copy Names' changes copy struct name to 'Charlie' and copy class name to 'Dave'.
Original struct name remains 'Alice' because structs are copied values.
Original class name changes to 'Dave' because classes share references.
Stretch Goal
Add a toggle to switch between showing original and copy names for both struct and class.
💡 Hint
Use a @State Boolean to toggle and conditionally show either original or copy names in the UI.

Practice

(1/5)
1. Which statement correctly describes the difference between struct and class in Swift?
easy
A. class is copied on assignment but struct is shared.
B. struct is a value type and class is a reference type.
C. struct supports inheritance but class does not.
D. struct can only have stored properties, class cannot.

Solution

  1. Step 1: Understand value vs reference types

    In Swift, struct is a value type, meaning it is copied when assigned or passed around. class is a reference type, meaning instances share the same reference.
  2. Step 2: Evaluate each option

    struct is a value type and class is a reference type. correctly states the difference. struct supports inheritance but class does not. is wrong because struct does not support inheritance. class is copied on assignment but struct is shared. reverses the behavior. struct can only have stored properties, class cannot. is false because class can have stored properties.
  3. Final Answer:

    struct is a value type and class is a reference type. -> Option B
  4. Quick Check:

    Value type = struct, Reference type = class [OK]
Hint: Remember: structs copy, classes share references [OK]
Common Mistakes:
  • Confusing value and reference types
  • Thinking structs support inheritance
  • Assuming classes are copied on assignment
2. Which of the following is the correct way to declare a struct in Swift?
easy
A. class Person { var name: String }
B. struct Person: String { var name }
C. struct Person = { var name: String }
D. struct Person { var name: String }

Solution

  1. Step 1: Recall Swift struct syntax

    A struct is declared with the keyword struct, followed by the name and curly braces containing properties.
  2. Step 2: Check each option

    struct Person { var name: String } matches the correct syntax: struct Person { var name: String }. class Person { var name: String } uses class, not struct. struct Person = { var name: String } uses an invalid assignment syntax. struct Person: String { var name } incorrectly tries to inherit from String and misses type for name.
  3. Final Answer:

    struct Person { var name: String } -> Option D
  4. Quick Check:

    Struct declaration uses struct Name { } [OK]
Hint: Use 'struct Name { var property: Type }' for structs [OK]
Common Mistakes:
  • Using class keyword instead of struct
  • Incorrect syntax with equals sign
  • Missing type annotation for properties
3. Consider the following Swift code:
struct Point {
  var x: Int
  var y: Int
}

var p1 = Point(x: 1, y: 2)
var p2 = p1
p2.x = 5
print(p1.x)

What will be printed?
medium
A. 1
B. 5
C. 0
D. Compilation error

Solution

  1. Step 1: Understand struct copying behavior

    Since Point is a struct (value type), assigning p1 to p2 copies the data. They are independent.
  2. Step 2: Analyze mutation and print

    Changing p2.x to 5 does not affect p1.x. So p1.x remains 1. The print statement outputs 1.
  3. Final Answer:

    1 -> Option A
  4. Quick Check:

    Structs copy on assignment, so original stays unchanged [OK]
Hint: Structs copy on assignment; changes don't affect original [OK]
Common Mistakes:
  • Assuming p1.x changes when p2.x changes
  • Confusing structs with classes (reference types)
  • Expecting runtime error on mutation
4. The following Swift code tries to modify a property of a struct instance inside a function but causes a compile error:
struct Counter {
  var count: Int
}

func increment(counter: Counter) {
  counter.count += 1
}

What is the main reason for the error?
medium
A. Function parameter 'counter' is a constant by default
B. Struct properties cannot be modified inside functions
C. You cannot use '+=' operator on Int
D. Counter must be a class to modify properties

Solution

  1. Step 1: Understand function parameter mutability

    In Swift, function parameters are constants by default. You cannot modify them inside the function.
  2. Step 2: Analyze the error cause

    The parameter counter is a struct instance passed by value but immutable inside the function. Trying to change counter.count causes a compile error.
  3. Final Answer:

    Function parameter 'counter' is a constant by default -> Option A
  4. Quick Check:

    Function parameters are immutable unless marked inout [OK]
Hint: Function parameters are constants unless 'inout' is used [OK]
Common Mistakes:
  • Thinking structs can't have mutable properties
  • Believing '+=' is invalid for Int
  • Assuming classes are required for mutation
5. You want to create a Swift type to represent a user profile that can be shared and updated across your app without copying. Which should you choose and why?
struct UserProfile {
  var name: String
  var age: Int
}

class UserProfileClass {
  var name: String
  var age: Int
  init(name: String, age: Int) {
    self.name = name
    self.age = age
  }
}
hard
A. Use struct because it copies data and prevents accidental changes.
B. Use class because structs cannot have properties.
C. Use class because it shares references and updates reflect everywhere.
D. Use struct because classes cannot have initializers.

Solution

  1. Step 1: Identify sharing vs copying needs

    If you want updates to reflect everywhere (shared state), you need a reference type.
  2. Step 2: Match type to behavior

    class is a reference type, so instances are shared. struct copies data, so changes won't reflect across copies.
  3. Final Answer:

    Use class because it shares references and updates reflect everywhere. -> Option C
  4. Quick Check:

    Shared mutable state = class [OK]
Hint: Choose class for shared mutable data, struct for copies [OK]
Common Mistakes:
  • Choosing struct when shared updates are needed
  • Thinking classes can't have initializers
  • Believing structs can't have properties
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard