Link Menu Expand Document

Swift Programming

Variables Series · Lesson 4

Practical Example

Connect the concepts to real code by following a full mini-example that uses variables end to end.

Swift Programming Xcode iOS

What to focus on while watching

  • Track how each variable changes as the logic runs.
  • Notice how naming and type choices make the example easier to follow.
  • Relate each line of code back to the problem being solved.

Lesson Notes and Walkthrough

This lesson shows how variables work together in a realistic mini workflow. Instead of isolated lines, you will see how values flow from input to final result.

Scenario: Simple Shopping Total

Imagine a user adds items to a cart. We store count, price, and discount in variables, then calculate a final total.

var itemCount = 3
var pricePerItem: Double = 12.5
var discount: Double = 5.0

let subtotal = Double(itemCount) * pricePerItem
let total = subtotal - discount

print("Subtotal: \(subtotal)")
print("Total: \(total)")

Walkthrough

  1. Start with user-controlled values (itemCount, pricePerItem).
  2. Compute intermediate values (subtotal).
  3. Apply adjustments (discount).
  4. Print and verify output before moving on.

Why This Pattern Matters

  • It separates input values from calculated results.
  • It makes bugs easier to find because each value has one clear purpose.
  • It scales well when logic gets more complex.

You may also like

Practice: Practical Variables

~7 min Beginner

Goal: Update multiple variables to simulate a simple cart total.

Steps

  1. Start with item count and price per item.
  2. Calculate subtotal and then apply a discount.
  3. Print the final total in one line.

Expected Output

Final total: $17.0
Need a hint? Use Double values for prices and compute subtotal - discount.

Code

import Foundation

var itemCount = 2
var pricePerItem: Double = 10.0
var discount: Double = 3.0

let subtotal = Double(itemCount) * pricePerItem
let finalTotal = subtotal - discount

print("Final total: $\(finalTotal)")