0
0
Swiftprogramming~5 mins

Adding computed properties in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a computed property in Swift?
A computed property calculates a value each time it is accessed instead of storing it. It uses a getter and optionally a setter to compute the value dynamically.
Click to reveal answer
beginner
How do you define a read-only computed property in Swift?
You define a computed property with only a getter, like this:<br>
var area: Double {<br>  return width * height<br>}
This property calculates and returns the area without storing it.
Click to reveal answer
intermediate
Can computed properties have setters in Swift? What does that mean?
Yes, computed properties can have setters. This means you can assign a value to the property, and the setter will run code to update other properties or perform actions based on the new value.
Click to reveal answer
beginner
Why use computed properties instead of stored properties?
Computed properties save memory because they don’t store values. They always provide up-to-date values based on other data, making your code cleaner and more flexible.
Click to reveal answer
beginner
Example: How to add a computed property 'fullName' combining 'firstName' and 'lastName'?
You can write:<br>
var fullName: String {<br>  return "\(firstName) \(lastName)"<br>}
This property returns the full name by joining first and last names.
Click to reveal answer
What does a computed property in Swift do?
AIs only used for constants
BStores a fixed value in memory
CCalculates its value every time it is accessed
DCannot have a setter
Which keyword is used to define a computed property in Swift?
Avar
Blet
Cfunc
Dclass
Can a computed property have a setter in Swift?
AOnly inside classes
BNo, computed properties are read-only
COnly if marked with 'let'
DYes, to update other properties when assigned
What happens if you omit the setter in a computed property?
AThe property cannot be accessed
BThe property becomes read-only
CThe property stores a value
DThe code will not compile
Why might you choose a computed property over a stored property?
ATo always get up-to-date values without extra storage
BTo save the value permanently
CTo make the property constant
DTo avoid using functions
Explain what a computed property is and how it differs from a stored property in Swift.
Think about how the value is provided or stored.
You got /3 concepts.
    Write a simple example of a computed property that returns the full name by combining first and last names.
    Use string interpolation inside the getter.
    You got /3 concepts.