πŸŽ“ A1Learner
πŸ”
0 of 27 lessons completed

Swift Advanced Introduction

This course takes Swift further with concurrency and deeper type tools. Each lesson adds one idea and proves it with complete runnable programs.

A struct with a computed property

The struct stores a width and a height. The computed property multiplies them each time the area is read.

struct Room {
    var width: Int
    var height: Int
    var area: Int {
        width * height
    }
}
let room = Room(width: 4, height: 5)
print(room.width)
print(room.area)

An enum in a switch

The enum lists three levels. The switch prints a label for the level the constant holds.

enum Level {
    case low
    case medium
    case high
}
let level = Level.medium
switch level {
case .low:
    print("Low")
case .medium:
    print("Medium")
case .high:
    print("High")
}

A dictionary over sorted keys

The dictionary maps codes to counts. The loop walks the keys in sorted order so the prints always follow the same order.

let counts = ["b": 2, "a": 1, "c": 3]
for key in counts.keys.sorted() {
    print("\(key) \(counts[key] ?? 0)")
}

Example

struct Basket {
    var items: Int
    var priceEach: Int
    var total: Int {
        items * priceEach
    }
}
let basket = Basket(items: 3, priceEach: 7)
print(basket.total)

Key points

  • Concurrency lets a program start work and collect its result later.
  • Shared state can sit behind a guard that handles one request at a time.
  • Properties can gain reusable behavior that wraps a stored value.
  • Functions and types can adapt their shape while keeping their checks.
  • Memory rules decide how long a value stays alive and who can change it.
  • Every program in this course is complete and states its real output.

In this example, the basket stores a count of items and a price for each one. The computed total multiplies the two stored values. The print reads the total and shows 21.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does a computed property do in the opening programs?