As you read this lesson and try out the exercises below, you can add to the Data Types and Structures playground that you created in our previous class.
Individual variables or constants only go so far.
What if we want to describe, say, a person?
What attributes does a person have?
These might include:
name
hair
colour
age
height (in cm)
mass (in kg)
Definition of a structure
TIP
Try out each example below in your Xcode Playground to verify the result.
To do this with a code block, hover your mouse over the code block, then click the copy button .
You can then paste the code into your Playground using Command-V.
This is the definition of a structure:
struct Person { // MARK: Stored properties // These are properties that have an assigned value let age: Int let hairColour: String let name: String let heightInCentimetres: Double let massInKilograms: Double}
Action
Add the code shown above to your Data Types and Structures playground now.
A structure is a data type, just like String, Int, and Double are data types.
So by defining our own structure, we are literally creating a new data type in Swift!
Creating an instance
How do we use a structure, though?
To create an instance of a type, we must provide values for each property of the type.
Here, two instances of the Person data type are created, as constants:
Try creating an instance of the Person type named me to represent yourself. Make it a constant, using the let keyword, like the instances of the Person structure shown above.
Once an instance of a structure is created, we can “ask about” the values held in each property, and use these values in programs we author.
Action
Add the following code to the bottom of your Data Types and Structures playground and try it out.
me.age
What shows up in the results sidebar, at right?
Variables and constants
What happens if you try to change, or mutate, one of the properties of the structure?
Action
Add this code at the bottom of the playground:
me.age = 21
Remember, the structure was defined with the age property as a constant. This means the the value of age cannot ever change (cannot ever be mutated):
struct Person { // MARK: Stored properties // These are properties that have an assigned value let age: Int // Defined using "let", so it is constant let hairColour: String let name: String let heightInCentimetres: Double let massInKilograms: Double}
Action
Change the definition of the name constant so that it is variable – use var instead of let.
Now, try running your playground again – what happens?
We still cannot change the value of the age property because the instance of the Person structure itself was defined as a constant.
Action
Change the code that creates an instance of the Person named me in your playground, so that the instance is a variable, rather than a constant.
To summarize, a structure works like any other data type.
When an instance of a structure is declared as a constant, using the let keyword, that instance cannot be changed.
When an instance of a structure is declared as a variable, using the var keyword, and there are properties of that structure also declared as variables, we can change the values of individual properties.
Discussion
Discuss with a friend in class.
What other properties of the Person structure should be defined as variables?
To answer this question, consider whether the values those properties hold would change over time.
Make any necessary changes to the Person structure in your Xcode playground.
Exercise
Goal: Show you can define a structure, create instances, read properties, and reason about when to use let vs var for properties and for instances.
Pick a domain & define a structure
Choose one domain (or select your own): Book, Animal, VideoGame, Bicycle, Planet, Recipe.
Action
Create a new structure in your Data Types and Structures playground playground. Your struct must:
Have 5–7 stored properties with mixed types (String, Int, Double, Bool).
Use at least twolet properties (values that never change for this thing).
Use at least twovar properties (values that could change over time).
Use clear names and add one-line comments explaining each property’s purpose.
(Think carefully about which attributes are truly fixed vs changeable.)
Create two instances (constants)
Action
Make two instances of your structure using let, with realistic values that are different from each other.
Give each instance a short, descriptive constant name.
In the results sidebar, expand the instance to verify property values look correct.
Read properties
Action
Add 3–4 single-line expressions that read properties from both instances (for example, paperback.pageCount) and observe the values in the sidebar.
Add a brief inline comment for each explaining what is being read and why it makes sense.
Mutability experiments (property vs instance)
You will try to change some values and explain the results.
Action
4a. Attempt to change one of your let properties on one instance.
Predict the outcome in a comment, then run the code and write a one-sentence explanation of the actual error (use the wording Xcode gives you).
Action
4b. Attempt to change one of your var properties on one instance while the instance is a let.
Predict → run → explain the result.
Action
4c. Now create a third instance of your structure using var.
Change a var property on this instance. Predict → run → confirm what happens and explain why this case is different from 4b.
(This section checks your understanding of “property mutability” vs “instance mutability.”)
Mini‑reflection
Action
In 3–4 sentences at the bottom of your playground:
Which of your properties were hardest to classify as let vs var, and why?
In your own words, explain the difference between:
a property being let vs var, and
an instance being declared with let vs var.
Please add your results for these exercises both as code blocks in Notion (type /code to create one) and by using screenshots of your playground in Xcode.
Solutions
Here is an example solution to the exercises above. This is just one possible set of answers. Please review, comparing these to your own work. Ask questions of Mr. Gordon through your portfolio on Notion using @Russell Gordon as needed. You will see a (somewhat shorter) question like this on Monday’s mini-test. Note that the mini-test on Monday will be written on paper – no computers or other reference material permitted.
SOLUTION
// MARK: Exercise Solutions — Structures (Movie domain)// Goal: Define a structure, create instances, read properties, reason about let vs var// NOTE: Lines that would cause compile errors are commented out;// the exact Xcode error text is included.// 1) Pick a domain & define a structure// Domain chosen: Moviestruct Movie { // Fixed identity details — these never change for a given film let title: String // The film’s public title let director: String // Primary credited director let releaseYear: Int // Year first released to the public let runtimeMinutes: Int // Total runtime in minutes // Mutable, time-dependent details — these can change var userRating: Double // Audience rating out of 10 that can change over time var isInTheatres: Bool // Whether it’s currently in theatres var boxOfficeMillions: Double// Worldwide gross to date in millions of USD}// 2) Create two instances (constants)let arrival = Movie( title: "Arrival", director: "Denis Villeneuve", releaseYear: 2016, runtimeMinutes: 116, userRating: 9.2, isInTheatres: false, boxOfficeMillions: 203.4)let crawdads = Movie( title: "Where the Crawdads Sing", director: "Olivia Newman", releaseYear: 2022, runtimeMinutes: 125, userRating: 7.4, isInTheatres: false, boxOfficeMillions: 144.3)// 3) Read propertiesarrival.title // What is the title of the first film? → Confirms identitycrawdads.director // Who directed the second film? → Checks a String propertyarrival.runtimeMinutes // How long is "Arrival"? → Reads a fixed Int propertycrawdads.boxOfficeMillions // How much has "Crawdads" grossed so far (in $M)? // → Reads a Doublearrival.userRating // What’s the current audience rating for "Arrival"? // → Reads a mutable Double// 4) Mutability experiments (property vs instance)// 4a) Try to change a `let` property on one instance.// Prediction: Not allowed. You cannot assign to a constant property.// Actual result (Xcode error):// error: Cannot assign to property: 'runtimeMinutes' is a 'let' constant// arrival.runtimeMinutes = 118// 4b) Try to change a `var` property on an instance that itself was declared with `let`.// Prediction: Not allowed. Even though the property is `var`, the whole instance is// immutable.// Actual result (Xcode error):// error: Cannot assign to property: 'arrival' is a 'let' constant// arrival.userRating = 9.4// 4c) Now declare a third instance with `var`, then change a `var` property.var featured = Movie( title: "Dune (2021)", director: "Denis Villeneuve", releaseYear: 2021, runtimeMinutes: 155, userRating: 8.6, isInTheatres: false, boxOfficeMillions: 402.1)// This succeeds because `featured` (the instance) is mutable and `userRating` is a `var`.featured.userRating = 8.8 // OK: instance is `var` and property is `var`featured.isInTheatres = true // OK: toggling current theatrical status// Explanation: In 4b the instance was a `let`, so no properties could be mutated.// In 4c the instance is a `var`, so its `var` properties can change.// 5) Mini-reflection (3–4 sentences)//// The hardest properties to classify were things like// boxOfficeMillions and userRating because they represent// evolving, time-based facts rather than the film’s core// identity. Title, director, releaseYear, and// runtimeMinutes fit naturally as `let` because they// define the work itself and don’t change for a given// cut. A property being `let` vs `var` describes whether// that single field may change for an instance.// Declaring an instance with `let` vs `var` controls// whether *any* of its mutable (`var`) properties can be// modified at all; a `let` instance freezes the entire// value, even if it has `var` properties in its type.