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

Swift Intermediate Introduction

This course builds on the beginner course with deeper tools for everyday programs. Each lesson adds one idea and proves it with complete runnable programs.

A stored closure, revisited

The constant holds a closure that triples its input. Two calls print 12 and then 30.

let triple = { (n: Int) -> Int in n * 3 }
print(triple(4))
print(triple(10))

A small struct

The struct groups a code and a price into one value. The prints read the two stored parts back.

struct Ticket {
    var code: String
    var price: Int
}
let ticket = Ticket(code: "A12", price: 15)
print(ticket.code)
print(ticket.price)

A closure that changes a variable

The closure adds each input into a variable declared before it. Two calls lift the total to 12.

var total = 0
let add = { (n: Int) in total += n }
add(5)
add(7)
print(total)

Example

enum Light {
    case red
    case green
}
let light = Light.green
switch light {
case .red:
    print("Stop")
case .green:
    print("Go")
}

Key points

  • Some closures keep working after the function that received them has returned.
  • Enums in this course carry data inside their cases.
  • Properties can compute a value on demand and react when a value changes.
  • Protocols and generics let one piece of code work with many types.
  • Errors appear in this course as values a program can pass around and handle.
  • Every program in this course is complete and states its real output.

In this example, the light value holds the green case of the enum. The switch matches that case and prints Go. Later lessons give cases like these data of their own to carry.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which topic does this course add for closures?