Podcast
Questions and Answers
What is a key capability that Swift extensions provide, especially useful when you lack access to the original source code of a type?
What is a key capability that Swift extensions provide, especially useful when you lack access to the original source code of a type?
- Retroactive modeling, adding functionality to existing types. (correct)
- Creating entirely new classes from scratch.
- Modifying the underlying binary code of compiled libraries.
- Changing the fundamental data structures of Swift's core libraries.
Extensions, unlike Objective-C categories, have names.
Extensions, unlike Objective-C categories, have names.
False (B)
Using the keyword extension
, show the syntax to add new functionality to a type named ExampleType
.
Using the keyword extension
, show the syntax to add new functionality to a type named ExampleType
.
extension ExampleType {
// new functionality to add to ExampleType goes here
}
Extensions can extend an existing _____ type to make it adopt one or more protocols.
Extensions can extend an existing _____ type to make it adopt one or more protocols.
Match the extension capabilities with their description:
Match the extension capabilities with their description:
Which of the following functionalities can be added to a class using extensions in Swift?
Which of the following functionalities can be added to a class using extensions in Swift?
When an extension adds an initializer to a value type with default values for all stored properties, you cannot call the default initializer from within the extension's initializer.
When an extension adds an initializer to a value type with default values for all stored properties, you cannot call the default initializer from within the extension's initializer.
Write the code to add an initializer to a Rect
structure (declared in another module) that takes a center
of type Point
and a size
of type Size
. The initializer must call an initializer from the defining module.
Write the code to add an initializer to a Rect
structure (declared in another module) that takes a center
of type Point
and a size
of type Size
. The initializer must call an initializer from the defining module.
Instance methods added with an extension that modify self
or its properties must mark the instance method as ________.
Instance methods added with an extension that modify self
or its properties must mark the instance method as ________.
Match the following code snippets with their functionalities:
Match the following code snippets with their functionalities:
What does 'retroactive modeling' refer to in the context of Swift extensions?
What does 'retroactive modeling' refer to in the context of Swift extensions?
Extensions can add stored properties to existing types.
Extensions can add stored properties to existing types.
Show the syntax to extend a type named MyArray
to conform to a protocol named Printable
and another protocol named Debuggable
.
Show the syntax to extend a type named MyArray
to conform to a protocol named Printable
and another protocol named Debuggable
.
When adding protocol conformance with an extension, you write the protocol names the same way as you write them for a _____ or _____
When adding protocol conformance with an extension, you write the protocol names the same way as you write them for a _____ or _____
Match the following units of length with their equivalent in meters, as defined in the example extension of the Double
type:
Match the following units of length with their equivalent in meters, as defined in the example extension of the Double
type:
Which keyword is NOT used when defining read-only computed properties in an extension?
Which keyword is NOT used when defining read-only computed properties in an extension?
Extensions can add new designated initializers to a class.
Extensions can add new designated initializers to a class.
If you use an extension to add an initializer to a structure that was declared in another module, what restriction applies to the new initializer?
If you use an extension to add an initializer to a structure that was declared in another module, what restriction applies to the new initializer?
The repetitions(task:)
method in the example uses a trailing closure syntax. The parameter type is () -> _____
.
The repetitions(task:)
method in the example uses a trailing closure syntax. The parameter type is () -> _____
.
Match the code snippet with its description:
Match the code snippet with its description:
What must structure and enumeration methods do to modify self
or its properties when the methods are part of an extension?
What must structure and enumeration methods do to modify self
or its properties when the methods are part of an extension?
Extensions can be used to override existing methods in a class.
Extensions can be used to override existing methods in a class.
Given let number = 123456
, what will number[2]
return, based on the Int
extension that retrieves the digit at a given index?
Given let number = 123456
, what will number[2]
return, based on the Int
extension that retrieves the digit at a given index?
In the example provided, the Kind
enumeration defines three cases: negative
, _____
, and positive
.
In the example provided, the Kind
enumeration defines three cases: negative
, _____
, and positive
.
Match the integer with the appropriate Kind
case according to the provided extension:
Match the integer with the appropriate Kind
case according to the provided extension:
What does the terminator: ""
argument do in the printIntegerKinds(_:)
function?
What does the terminator: ""
argument do in the printIntegerKinds(_:)
function?
Extensions can add entirely new types to a Swift program.
Extensions can add entirely new types to a Swift program.
Write code to extend the built-in String
type with a computed property called isPalindrome
that returns a Bool
indicating whether the string is a palindrome.
Write code to extend the built-in String
type with a computed property called isPalindrome
that returns a Bool
indicating whether the string is a palindrome.
When extending a generic type to conditionally add functionality, you use a _____ clause to specify the conditions under which the extension applies.
When extending a generic type to conditionally add functionality, you use a _____ clause to specify the conditions under which the extension applies.
Match each computed property added to the Double
type with the correct formula:
Match each computed property added to the Double
type with the correct formula:
When adding an initializer to a value type via an extension, under what circumstance can you NOT call the default initializer and memberwise initializer for that value type from within your extension’s initializer?
When adding an initializer to a value type via an extension, under what circumstance can you NOT call the default initializer and memberwise initializer for that value type from within your extension’s initializer?
Adding a mutating method to an enum
within an extension requires the same mutating
keyword as within the original enum
definition.
Adding a mutating method to an enum
within an extension requires the same mutating
keyword as within the original enum
definition.
Explain the purpose of the Kind
enumeration within the context of the Int
extension example, and describe how it's used.
Explain the purpose of the Kind
enumeration within the context of the Int
extension example, and describe how it's used.
Extensions are similar to _____ in Objective-C, but unlike them, Swift extensions don’t have names.
Extensions are similar to _____ in Objective-C, but unlike them, Swift extensions don’t have names.
Match each structure with its stored properties:
Match each structure with its stored properties:
Which statement is true regarding the application of extensions for protocol conformance?
Which statement is true regarding the application of extensions for protocol conformance?
It is possible to define a new deinitializer within an extension.
It is possible to define a new deinitializer within an extension.
Outline the steps required to add a subscript to Swift's built-in String
type that returns the character at a specific index, handling potential index out-of-bounds errors gracefully.
Outline the steps required to add a subscript to Swift's built-in String
type that returns the character at a specific index, handling potential index out-of-bounds errors gracefully.
Extensions in Swift support the concept of _____ modeling, which is particularly useful for modifying types when you don't have access to their original source code.
Extensions in Swift support the concept of _____ modeling, which is particularly useful for modifying types when you don't have access to their original source code.
Match the code with the functionality that the code creates:
Match the code with the functionality that the code creates:
Flashcards
What are extensions in Swift?
What are extensions in Swift?
Extensions add new functionality to existing classes, structures, enumerations, or protocol types, even without access to the original source code.
What kind of properties can extensions add?
What kind of properties can extensions add?
Extensions can add computed instance properties and computed type properties.
What kind of methods can be added via extensions?
What kind of methods can be added via extensions?
Extensions can define instance methods and type methods to existing types.
What initializers can extensions add?
What initializers can extensions add?
Signup and view all the flashcards
Can extensions define nested types?
Can extensions define nested types?
Signup and view all the flashcards
Can extensions add protocol conformance?
Can extensions add protocol conformance?
Signup and view all the flashcards
How do you declare an extension?
How do you declare an extension?
Signup and view all the flashcards
How to conditionally extend a generic type?
How to conditionally extend a generic type?
Signup and view all the flashcards
Are computed properties added by extensions read-only?
Are computed properties added by extensions read-only?
Signup and view all the flashcards
How can you change an instance in an extension method?
How can you change an instance in an extension method?
Signup and view all the flashcards
Can extensions add subscripts?
Can extensions add subscripts?
Signup and view all the flashcards
Can extensions add nested enumerations?
Can extensions add nested enumerations?
Signup and view all the flashcards
How can extensions return enumeration cases?
How can extensions return enumeration cases?
Signup and view all the flashcards
Study Notes
- Extensions add new functionality to existing class, structure, enumeration, or protocol types.
- Extensions enable retroactive modeling, allowing extension of types without original source code access.
- Swift extensions are similar to categories in Objective-C but lack names.
- Extensions can add computed instance and type properties.
- Extensions can define instance and type methods.
- Extensions can provide new initializers.
- Extensions can define subscripts.
- Extensions can define and use new nested types.
- Extensions can make an existing type conform to a protocol.
- Protocols can be extended to provide implementations or add functionality.
Extension Syntax
- Extensions are declared using the
extension
keyword.
extension SomeType {
// new functionality to add to SomeType goes here
}
- Extensions can enable a type to adopt one or more protocols.
extension SomeType: SomeProtocol, AnotherProtocol {
// implementation of protocol requirements goes here
}
- Extensions can extend generic types.
- Extensions can conditionally add functionality to a generic type using a generic where clause.
Computed Properties
- Extensions can add computed instance and type properties.
extension Double {
var km: Double { return self * 1_000.0 }
var m: Double { return self }
var cm: Double { return self / 100.0 }
var mm: Double { return self / 1_000.0 }
var ft: Double { return self / 3.28084 }
}
let oneInch = 25.4.mm
print("One inch is \(oneInch) meters")
// Prints "One inch is 0.0254 meters"
let threeFeet = 3.ft
print("Three feet is \(threeFeet) meters")
// Prints "Three feet is 0.914399970739201 meters"
- Computed properties in extensions allow treating
Double
values as specific length units. - The
m
property returnsself
, interpreting aDouble
of1.0
as "one meter." - Other unit properties convert values to meters (e.g.,
km
multiplies by 1,000.0). ft
property divides the Double value by 3.28084 to convert it from feet to meters.- These properties are read-only and omit the
get
keyword for brevity. - The return value is of type
Double
and can be used in mathematical calculations wherever aDouble
is accepted.
let aMarathon = 42.km + 195.m
print("A marathon is \(aMarathon) meters long")
// Prints "A marathon is 42195.0 meters long"
Initializers
- Extensions can add new initializers to existing types, enabling the use of custom types as initializer parameters.
- Extensions can add new convenience initializers to a class, but not designated initializers or deinitializers.
- Designated initializers and deinitializers must be part of the original class implementation.
- Extensions adding initializers to value types with default values can call the default and memberwise initializers from within the extension's initializer.
struct Size {
var width = 0.0, height = 0.0
}
struct Point {
var x = 0.0, y = 0.0
}
struct Rect {
var origin = Point()
var size = Size()
}
- Structures like
Rect
with default values for all properties automatically receive default and memberwise initializers.
let defaultRect = Rect()
let memberwiseRect = Rect(origin: Point(x: 2.0, y: 2.0),
size: Size(width: 5.0, height: 5.0))
- Extensions can provide additional initializers.
extension Rect {
init(center: Point, size: Size) {
let originX = center.x - (size.width / 2)
let originY = center.y - (size.height / 2)
self.init(origin: Point(x: originX, y: originY), size: size)
}
}
- The new initializer calculates the origin point based on the center and size and then calls the memberwise initializer.
let centerRect = Rect(center: Point(x: 4.0, y: 4.0),
size: Size(width: 3.0, height: 3.0))
// centerRect's origin is (2.5, 2.5) and its size is (3.0, 3.0)
Methods
- Extensions can add new instance and type methods to existing types.
extension Int {
func repetitions(task: () -> Void) {
for _ in 0.. Void`, indicating a function with no parameters and no return value.
- The `repetitions(task:)` method can be called on any integer to perform a task a specific number of times.
3.repetitions { print("Hello!") } // Hello! // Hello! // Hello!
### Mutating Instance Methods
- Instance methods can modify the instance itself.
- Structure and enumeration methods that modify `self` or its properties must be marked as `mutating`.
extension Int { mutating func square() { self = self * self } } var someInt = 3 someInt.square() // someInt is now 9
### Subscripts
- Extensions can add new subscripts to an existing type.
extension Int { subscript(digitIndex: Int) -> Int { var decimalBase = 1 for _ in 0.. 0: return.positive default: return.negative } } }
- This adds a new nested enumeration to `Int` called `Kind`, expressing the number's sign.
- A new computed instance property called `kind` returns the appropriate `Kind` enumeration case for that integer.
func printIntegerKinds(_ numbers: [Int]) { for number in numbers { switch number.kind { case.negative: print("- ", terminator: "") case.zero: print("0 ", terminator: "") case.positive: print("+ ", terminator: "") } } print("") } printIntegerKinds([3, 19, -27, 0, -6, 0, 7]) // Prints "+ + - 0 - 0 + "
- The `printIntegerKinds(_:)` function takes an array of `Int` values and prints the sign of each integer.
Studying That Suits You
Use AI to generate personalized quizzes and flashcards to suit your learning preferences.