SWIFT / CHAPTER 01

Constants, variables, and expressions

Beginner

Choose bindings and trace typed Swift expressions.

By the end of this chapter

  • Distinguish let from var
  • Predict integer arithmetic
  • Build strings with interpolation

The idea

Swift uses let for a constant binding and var for a variable that can be reassigned. The compiler can infer a type from an initializer, but later assignments must remain compatible with that type. Integer and floating-point arithmetic are distinct. An integer division does not retain a fractional remainder, and Swift generally requires explicit numeric conversions when combining different numeric types.

String interpolation embeds expressions inside text using a backslash and parentheses. It is useful for labels without changing the underlying values. Swift strings represent Unicode text, so their positions are not ordinary integer array indices. Use supported string operations, and do not assume that the number of encoded bytes equals the number of visible characters.

Swift example
let tasks = 11
let days = 3
let average = Double(tasks) / Double(days)
print(tasks / days)
print("Tasks: (tasks)")
print(average > 3.5)
Result
3
Tasks: 11
true

Integer division yields three. Explicit conversions enable the fractional average, and interpolation includes the unchanged task count in a label.

Try it yourself

Create a constant project name and a mutable completed count, then print an interpolated status.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

What is printed?
var count = 3
let saved = count
count += 2
print(saved)