Properties in Swift

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson
Download our mobile app to listen on the go
Get App

Questions and Answers

What distinguishes stored properties from computed properties?

  • Stored properties store a value directly, while computed properties calculate a value. (correct)
  • Stored properties are associated with the type itself, whereas computed properties are associated with instances of a particular type.
  • Stored properties can only be constants, while computed properties can be variables.
  • Stored properties are only available in classes, while computed properties are available in structures and enumerations.

Structures are reference types, so when an instance of a structure is assigned to a constant, its variable properties can still be modified.

False (B)

What keyword is used to declare a lazy stored property?

lazy

A computed property with a getter but no setter is known as a ______ computed property.

<p>read-only</p> Signup and view all the answers

Match the property observer with its description:

<p><code>willSet</code> = Called just before a property's value is stored. <code>didSet</code> = Called immediately after a property's value is stored.</p> Signup and view all the answers

Which of the following is NOT a place where you can add property observers?

<p>Computed properties that you define. (D)</p> Signup and view all the answers

Property observers are called only when the new value of a property is different from its current value.

<p>False (B)</p> Signup and view all the answers

If a computed property's setter doesn't define a name for the new value to be set, what default name is used?

<p><code>newValue</code></p> Signup and view all the answers

The keyword ______ is used to define type properties.

<p><code>static</code></p> Signup and view all the answers

Match the term with its description:

<p>Instance properties = Properties that belong to an instance of a particular type. Type properties = Properties that belong to the type itself, not to any one instance of that type.</p> Signup and view all the answers

What is the primary purpose of a property wrapper?

<p>To add a layer of separation between code that manages property storage and code that defines a property. (A)</p> Signup and view all the answers

You can apply a property wrapper to a global variable.

<p>False (B)</p> Signup and view all the answers

In a property wrapper, what is the name of the property that stores the wrapped value?

<p><code>wrappedValue</code></p> Signup and view all the answers

In addition to the wrapped value, a property wrapper can expose additional functionality by defining a ______.

<p>projected value</p> Signup and view all the answers

Match the term with the appropriate keyword:

<p>Overrideable computed type properties in classes = <code>class</code> Type properties in structures and enumerations = <code>static</code></p> Signup and view all the answers

Which of the following is true regarding lazy stored properties?

<p>They are initialized the first time they are accessed. (A)</p> Signup and view all the answers

In Swift, a property always has a corresponding instance variable that serves as its backing store.

<p>False (B)</p> Signup and view all the answers

What syntax is used to access a type property?

<p>Dot syntax</p> Signup and view all the answers

If you assign a value to a property within its own ______ observer, the new value that you assign replaces the one that was just set.

<p><code>didSet</code></p> Signup and view all the answers

Match the structure with its description from the example:

<p><code>Point</code> = Encapsulates the x- and y-coordinate of a point. <code>Size</code> = Encapsulates a width and a height. <code>Rect</code> = Defines a rectangle by an origin point and a size.</p> Signup and view all the answers

If you create an instance of a class and assign that instance to a constant, can you modify the instance's variable properties?

<p>Yes, because classes are reference types. (D)</p> Signup and view all the answers

It is possible for both willSet and didSet observers to be called when assigning a new value to a property.

<p>True (A)</p> Signup and view all the answers

What is the name of the default parameter passed to the willSet observer if a custom name is not specified?

<p><code>newValue</code></p> Signup and view all the answers

The name of a property wrapper's projected value is the same as the wrapped value, except it begins with a ______ sign.

<p>dollar</p> Signup and view all the answers

Match the initialization scenario with the SmallNumber initializer used:

<p>No initial value specified = <code>init()</code> Initial value specified using assignment = <code>init(wrappedValue:)</code> Initial value and maximum specified = <code>init(wrappedValue:maximum:)</code></p> Signup and view all the answers

Why might a DataManager class use a lazy stored property for its DataImporter instance?

<p>To avoid initializing the <code>DataImporter</code> if it's not needed, as initialization might be computationally expensive. (D)</p> Signup and view all the answers

In a read-only computed property, you must include the get keyword and its braces.

<p>False (B)</p> Signup and view all the answers

Using the example of AudioChannel, what happens if a channel’s audio signal comes in with a value higher than thresholdLevel?

<p>It will be capped to this threshold value</p> Signup and view all the answers

A Swift property does not have a corresponding ______ variable, and the backing store for a property isn't accessed directly.

<p>instance</p> Signup and view all the answers

Match term and Usage

<p>Global variables = Defined outside of any function, method, closure, or type context Local variables = Defined within a function, method, or closure context.</p> Signup and view all the answers

Given the SmallNumber property wrapper and the struct SomeStructure defined as:

`@propertyWrapper struct SmallNumber { private var number: Int private(set) var projectedValue: Bool

var wrappedValue: Int {
    get { return number }
    set {
        if newValue > 12 {
            number = 12
            projectedValue = true
        } else {
            number = newValue
            projectedValue = false
        }
    }
}

init() {
    self.number = 0
    self.projectedValue = false
}

} struct SomeStructure { @SmallNumber var someNumber: Int } var someStructure = SomeStructure()`

What will be the output of print(someStructure.someNumber, someStructure.$someNumber) after executing someStructure.someNumber = 15?

<p>12 true (A)</p> Signup and view all the answers

A type can have both stored and computed type properties.

<p>True (A)</p> Signup and view all the answers

In the context of property wrappers, what is the significance of the $ prefix?

<p>Indicates a projected value.</p> Signup and view all the answers

According to the example, ______ are useful for defining values that are universal to all instances of a particular type.

<p>Type properties</p> Signup and view all the answers

Match the class/struct with its correct description

<p><code>DataImporter</code> = Provides data importing functionality <code>DataManager</code> = Provides data management functionality</p> Signup and view all the answers

Which of the following is true about stored type properties?

<p>Stored type properties must be initialized with a default value. (C)</p> Signup and view all the answers

Local variables cannot have property observers.

<p>False (B)</p> Signup and view all the answers

What keyword allows subclasses to override the superclass’s implementation of a computed type property?

<p><code>class</code></p> Signup and view all the answers

When you access a projected value from code that’s part of the type, you can omit self. before the property name, just like accessing other ______.

<p>properties</p> Signup and view all the answers

Match the situation to the property type that will be most suitable:

<p>AudioChannel: The maximum threshold value that audio level can take = Stored type property Rect: Determine the center point of the rectangle. = Computed property StepCounter: Track the total number of steps someone takes = Stored Property with Property Observers</p> Signup and view all the answers

Given the following code:

struct MyStruct {
    static var myTypeProperty: Int = 5
    var myInstanceProperty: Int = 10
}

var instance1 = MyStruct()
var instance2 = MyStruct()

instance1.myInstanceProperty = 20
MyStruct.myTypeProperty = 15

print(instance1.myInstanceProperty, instance2.myInstanceProperty, MyStruct.myTypeProperty)

What will be printed?

<p>20 10 15 (B)</p> Signup and view all the answers

The purpose of property observers is to add a layer of separation between managing a property its storage.

<p>False (B)</p> Signup and view all the answers

What will happen if currentLevel is set to 15 in the following code, assuming AudioChannel.thresholdLevel is 10?

struct AudioChannel {
    static let thresholdLevel = 10
    var currentLevel: Int = 0 {
        didSet {
            if currentLevel > AudioChannel.thresholdLevel {
                currentLevel = AudioChannel.thresholdLevel
            }
        }
    }
}

var channel = AudioChannel()
channel.currentLevel = 15

print(channel.currentLevel)

<p>currentLevel will be set to 10</p> Signup and view all the answers

Flashcards

Properties

Associate values with a class, structure, or enumeration.

Stored properties

Store constant or variable values as part of an instance.

Computed properties

Calculate a value instead of storing it.

Type properties

Properties associated with the type itself.

Signup and view all the flashcards

Property Observers

Monitor and respond to changes in a property's value.

Signup and view all the flashcards

Property Wrapper

Reuse code in the getter and setter of multiple properties.

Signup and view all the flashcards

Stored Property

A constant or variable stored as part of a class or structure instance.

Signup and view all the flashcards

Lazy Stored Property

Stored property that's only calculated the first time it's accessed.

Signup and view all the flashcards

Computed Properties

Properties that calculate rather than store a value, with a getter and optionally a setter.

Signup and view all the flashcards

Read-Only Computed Property

Computed property that only has a getter, so its value can be retrieved but not set directly.

Signup and view all the flashcards

Property Observers

Observe and respond to changes in a property's value before and after it's set.

Signup and view all the flashcards

Property Wrapper

Adds a layer of separation to manage how a property is stored and accessed.

Signup and view all the flashcards

Projected Value

A property wrapper feature to expose additional functionality.

Signup and view all the flashcards

Global Variables

Variables defined outside of any function, method, closure, or type context.

Signup and view all the flashcards

Local Variables

Variables defined within a function, method, or closure context.

Signup and view all the flashcards

Type Properties

Belong to the type itself, not an instance. Shared across all instances.

Signup and view all the flashcards

Instance Variable

The value or reference is stored as part of a class instance.

Signup and view all the flashcards

Rects Center

Enables you to work with a rectangles center as if it were a real stored property.

Signup and view all the flashcards

Instance Properties

Properties that belong to a type rather than a particular instance of that type.

Signup and view all the flashcards

Study Notes

  • Properties associate values with classes, structures, or enumerations.
  • Stored properties store values as part of an instance.
  • Computed properties calculate a value instead of storing it.
  • Classes and structures provide stored properties.
  • Classes, structures, and enumerations provide computed properties.
  • Type properties are associated with the type itself, not an instance.
  • Property observers monitor changes in a property’s value.
  • Property wrappers reuse code in the getter and setter of multiple properties.

Stored Properties

  • The simplest form of a stored property is a constant or variable stored as part of a class or structure instance.
  • Stored properties can be variable (using var) or constant (using let).
  • Default values can be provided for stored properties.
  • Initial values can be set or modified during initialization, even for constant stored properties.
  • Instances of FixedLengthRange have a variable stored property firstValue and a constant stored property length.

Stored Properties of Constant Structure Instances

  • If a structure instance is assigned to a constant, its properties can't be modified, even if they are variable properties.
  • This behavior is due to structures being value types.
  • When a value type instance is marked as constant, all its properties are also constant.
  • Classes are reference types, so variable properties of an instance assigned to a constant can still be changed.

Lazy Stored Properties

  • A lazy stored property's initial value is not calculated until its first use.
  • Use the lazy modifier before the property declaration.
  • Lazy properties are useful when the initial value depends on outside factors or requires complex setup.
  • DataImporter takes a nontrivial amount of time to initialize.
  • The importer property is only created when first accessed, not when the DataManager instance is created.

Stored Properties and Instance Variables

  • Swift unifies properties and instance variables into a single property declaration.
  • Properties don't have corresponding instance variables.
  • The backing store for a property is not directly accessed.
  • All property information is defined in one location within the type's definition.

Computed Properties

  • Classes, structures, and enumerations can define computed properties that don't store a value.
  • Computed properties provide a getter and an optional setter to indirectly retrieve/set other properties/values.
  • Rect structure calculates the center from its origin and size, instead of storing it.
  • The square variable is initialized with an origin point of (0, 0), and a width and height of 10.
  • The square variable’s center property is then accessed through dot syntax (square.center), which causes the getter for center to be called, to retrieve the current property value, calculating and returning a new Point to represent the center of the square.

Shorthand Setter Declaration

  • If a setter doesn't name the new value, the default name newValue is used.

Shorthand Getter Declaration

  • If a getter's body is a single expression, it implicitly returns that expression.
  • Omitting the return from a getter follows the same rules as omitting return from a function.

Read-Only Computed Properties

  • A computed property with only a getter is a read-only computed property.
  • It returns a value but can't be set to a different value.
  • The get keyword and its braces can be removed for simpler declaration.

Property Observers

  • Property observers respond to changes in a property’s value.
  • Called every time a property’s value is set, even if the new value is the same.
  • Can be added to stored properties you define, stored properties you inherit, and computed properties you inherit.
  • For computed properties that you define, use the property’s setter to observe and respond to value changes, instead of trying to create an observer.
  • willSet is called just before the value is stored.
  • didSet is called immediately after the new value is stored.
  • willSet receives the new value as newValue (or a custom name).
  • didSet receives the old value as oldValue (or a custom name).
  • Assigning a value to a property within its own didSet observer replaces the value that was just set.

Property Wrappers

  • Property wrappers add a layer of separation between code that manages how a property is stored and the code that defines a property.
  • A property wrapper defines a wrappedValue property.
  • Apply a wrapper to a property by writing the wrapper’s name before the property as an attribute (@).
  • The compiler synthesizes code for storage and access through the wrapper.
  • _height and _width properties store an instance of the property wrapper, TwelveOrLess.
  • The getter and setter for height and width wrap access to the wrappedValue property.

Setting Initial Values for Wrapped Properties

  • If no initial value is specified, Swift uses the init() initializer to set up the wrapper.
  • When an initial value is included for the property, Swift uses the init(wrappedValue:) initializer to set up the wrapper.
  • When arguments are written in parentheses, Swift uses the initializer that accepts those arguments.

Projecting a Value From a Property Wrapper

  • A property wrapper can expose additional functionality by defining a projected value, with a name starting with $.
  • Writing someStructure.$someNumber accesses the wrapper’s projected value.

Global and Local Variables

  • Capabilities for computing and observing properties are available to global and local variables.
  • Global variables are defined outside any function, method, closure, or type context.
  • Local variables are defined within a function, method, or closure context.
  • You can apply a property wrapper to a local stored variable, but not to a global variable or a computed variable.

Type Properties

  • Instance properties belong to an instance of a particular type.
  • Type properties belong to the type itself, not any one instance.
  • There is only one copy of type properties.
  • Useful for values universal to all instances of a type.
  • Stored type properties can be variables or constants.
  • Computed type properties are always declared as variable properties.

Type Property Syntax

  • Type properties are written as part of the type’s definition.
  • Defined with the static keyword.
  • For computed type properties in classes, use class to allow subclasses to override.

Querying and Setting Type Properties

  • Type properties are queried and set with dot syntax on the type itself, not an instance.
  • If you set the currentLevel of the left channel to 7, you can see that the maxInputLevelForAllChannels type property is updated to equal 7.

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

More Like This

Swift Programming Basics Tutorial
25 questions
Swift UI: Ventajas y Aspectos Básicos de Xcode
10 questions
Bootcamp Full Stack Swift 2024
40 questions
Use Quizgecko on...
Browser
Browser