Um momento
0x60Lesson 7 of 7

Model data with structs and protocols

Create custom types and reusable behavior contracts.

15 min 5-question quiz 1 code exercise
By the end of this lesson you can
  • Define a struct, conform to a protocol, and call methods on values.

Structs are first-class value types in Swift and are ideal for modeling data. Protocols define required properties and methods. A type that conforms to a protocol can be used anywhere that protocol is expected, enabling clean, composable design.

main.swift
1protocol Describable {
2    func describe() -> String
3}
4
5struct Task: Describable {
6    let title: String
7    func describe() -> String {
8        "Task: \(title)"
9    }
10}
11
12print(Task(title: "Practice Swift").describe())
Output
Task: Practice Swift

Because structs are value types, assigning one variable to another copies the value. This makes ownership and mutation easier to reason about than shared mutable reference state.

Key takeaways

  • Define a struct, conform to a protocol, and call methods on values.

  • Swift favors clear intent and safe defaults.

  • Compiler feedback is part of the learning loop.

Lesson quiz

5 questions · pass with 4 correct · up to 50 XP

Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.

Practice: write Swift

These run for real. Write the program, press Run tests, and read what the compiler tells you - learning to read compiler messages is half of learning C.

Exercise 1

Describe a book struct

+25 XP

Create Book with a title property and describe() method that returns Book: <title>. Read a title and print describe().

  • Simple title
main.swift
Loading editor…

Swift lessons are authored for Swift 6.4; exercises run on Swift 6.0.1 via Wandbox, a free public service. Your source code and test input are sent to that service.

Questions about this lesson

Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.

Loading posts…

Gostou da aula? 😆👍
Apoie nosso trabalho com uma doação: