0
0
Swiftprogramming~5 mins

Adding initializers via extension in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is an extension in Swift?
An extension in Swift adds new functionality to an existing class, struct, enum, or protocol without modifying the original source code.
Click to reveal answer
beginner
Can you add initializers to a struct using an extension in Swift?
Yes, you can add new initializers to a struct using an extension, allowing you to create instances in new ways without changing the original struct definition.
Click to reveal answer
intermediate
Why can't you add designated initializers to a class via extension in Swift?
Swift does not allow adding designated initializers to classes via extensions because it could break the class's initialization rules and safety guarantees.
Click to reveal answer
intermediate
What is the difference between a convenience initializer and a designated initializer in Swift?
A designated initializer fully initializes all properties and calls a superclass initializer. A convenience initializer calls another initializer in the same class and provides a shortcut for common initialization.
Click to reveal answer
beginner
Show a simple example of adding an initializer to a struct using an extension in Swift.
struct Point { var x: Int; var y: Int } extension Point { init(value: Int) { self.x = value self.y = value } } // Now you can create Point(value: 5) to set both x and y to 5.
Click to reveal answer
Which of the following can you add via extension in Swift?
ANew initializers to a struct
BDesignated initializers to a class
CStored properties
DDeinitializers
What keyword is used to define an extension in Swift?
Aadd
Bextend
Cextension
Dinclude
Why can't you add stored properties in an extension?
ABecause stored properties are deprecated
BBecause extensions can only add computed properties and methods
CBecause Swift does not support extensions
DBecause stored properties require memory allocation which extensions can't do
Which initializer type can you add to a class via extension?
AConvenience initializer
BDesignated initializer
CDeinitializer
DStored property initializer
What happens if you add an initializer in an extension that duplicates an existing initializer?
AThe new initializer overrides the old one
BCompilation error due to duplicate initializers
CBoth initializers coexist without issues
DThe program crashes at runtime
Explain how to add an initializer to a struct using an extension in Swift and why this might be useful.
Think about how extensions let you add new ways to create instances without changing the original struct.
You got /4 concepts.
    Describe the limitations of adding initializers via extensions for classes in Swift.
    Consider Swift's rules about class initialization and safety.
    You got /3 concepts.