0
0
Swiftprogramming~5 mins

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 does not store a value directly. Instead, it provides a getter and optionally a setter to calculate a value when accessed or set.
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 and no setter. For example:<br>
var area: Double {<br>  return width * height<br>}
Click to reveal answer
intermediate
Can computed properties have side effects in Swift?
Yes, computed properties can run code inside their getter or setter, so they can have side effects like logging or updating other values.
Click to reveal answer
beginner
What is the difference between stored and computed properties?
Stored properties hold actual values in memory. Computed properties calculate values on demand without storing them.
Click to reveal answer
intermediate
Show an example of a computed property with both getter and setter in Swift.
Example:<br>
var temperatureCelsius: Double {<br>  get { return (temperatureFahrenheit - 32) * 5 / 9 }<br>  set { temperatureFahrenheit = newValue * 9 / 5 + 32 }<br>}
Click to reveal answer
What does a computed property in Swift do?
ACannot have a setter
BStores a fixed value in memory
CCalculates a value when accessed
DOnly stores strings
Which keyword is used to define a computed property in Swift?
Alet
Bvar
Cfunc
Dclass
Can a computed property have a setter in Swift?
AYes, to allow setting a new value
BNo, computed properties are read-only
COnly if marked with 'let'
DOnly inside structs
What happens if a computed property has only a getter?
AIt causes a compile error
BIt can be set
CIt stores a value
DIt is read-only
Which of these is NOT true about computed properties?
AThey store values directly
BThey can have side effects
CThey use get and set blocks
DThey calculate values on demand
Explain what a computed property is and how it differs from a stored property in Swift.
Think about how values are stored or calculated.
You got /3 concepts.
    Write a simple Swift computed property that calculates the area of a rectangle given width and height stored properties.
    Use a getter to calculate the area.
    You got /4 concepts.