0
0
Swiftprogramming~5 mins

Memberwise initializer in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a memberwise initializer in Swift?
A memberwise initializer is an automatically created initializer for structs in Swift. It lets you create an instance by providing values for each property directly.
Click to reveal answer
beginner
Does Swift automatically create a memberwise initializer for classes?
No, Swift does not automatically create a memberwise initializer for classes. It only does this for structs.
Click to reveal answer
beginner
Given this struct:<br>
struct Car {<br>  var make: String<br>  var year: Int<br>}
<br>How do you create a new Car instance using the memberwise initializer?
You create it by passing values for each property like this:<br><pre>let myCar = Car(make: "Toyota", year: 2020)</pre>
Click to reveal answer
intermediate
What happens if you add a custom initializer to a struct in Swift?
If you add a custom initializer, Swift does not generate the memberwise initializer automatically anymore. You have to write it yourself if you want it.
Click to reveal answer
beginner
Why is the memberwise initializer useful?
It saves time by letting you create instances quickly without writing your own initializer. It also makes your code cleaner and easier to read.
Click to reveal answer
Which Swift type automatically gets a memberwise initializer?
AEnum
BClass
CProtocol
DStruct
What do you need to provide when using a memberwise initializer?
AA closure
BOnly some properties
CValues for all properties
DNo values, it uses defaults
If you add a custom initializer to a struct, what happens to the memberwise initializer?
AIt is removed
BIt stays available
CIt becomes private
DIt throws an error
Can classes in Swift use memberwise initializers automatically?
ANo
BYes
COnly if they have no methods
DOnly if they inherit from NSObject
What is the main benefit of a memberwise initializer?
AAutomatically generate methods
BQuickly create instances with property values
CManage memory automatically
DEnforce access control
Explain what a memberwise initializer is and how it helps when creating struct instances in Swift.
Think about how you create a struct instance without writing your own initializer.
You got /4 concepts.
    Describe what happens to the memberwise initializer when you add a custom initializer to a Swift struct.
    Consider how Swift handles initializers when you add your own.
    You got /3 concepts.