Swift Extensions

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 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.

False (B)

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.

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

Match the extension capabilities with their description:

<p>Computed Properties = Add calculated values that don't store data directly. Initializers = Provide ways to create instances of the extended type. Methods = Add functions that perform actions on the extended type. Subscripts = Enable accessing parts of an instance using square bracket notation.</p> Signup and view all the answers

Which of the following functionalities can be added to a class using extensions in Swift?

<p>New convenience initializers (B)</p> Signup and view all the answers

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.

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

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.

<pre><code class="language-swift">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) } } </code></pre> Signup and view all the answers

Instance methods added with an extension that modify self or its properties must mark the instance method as ________.

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

Match the following code snippets with their functionalities:

<pre><code class="language-swift">extension Int { func repetitions(task: () -&gt; Void) { for _ in 0.. Void) { self = self * self } } ``` = Adds a method to square the value of an `Int`. ```swift extension Int { subscript(digitIndex: Int) -&gt; Int { var decimalBase = 1 for _ in 0.. 0: return .positive default: return .negative } } }``` = Determines if an integer is negative, zero, or positive. </code></pre> Signup and view all the answers

What does 'retroactive modeling' refer to in the context of Swift extensions?

<p>The capability to add new functionality to existing types, even without having access to the original source code. (B)</p> Signup and view all the answers

Extensions can add stored properties to existing types.

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

Show the syntax to extend a type named MyArray to conform to a protocol named Printable and another protocol named Debuggable.

<pre><code class="language-swift">extension MyArray: Printable, Debuggable { // implementation of protocol requirements goes here } </code></pre> Signup and view all the answers

When adding protocol conformance with an extension, you write the protocol names the same way as you write them for a _____ or _____

<p>class, structure</p> Signup and view all the answers

Match the following units of length with their equivalent in meters, as defined in the example extension of the Double type:

<p>1 km = 1000.0 meters 1 m = 1.0 meter 1 cm = 0.01 meter 1 mm = 0.001 meter</p> Signup and view all the answers

Which keyword is NOT used when defining read-only computed properties in an extension?

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

Extensions can add new designated initializers to a class.

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

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?

<p>The new initializer can’t access <code>self</code> until it calls an initializer from the defining module.</p> Signup and view all the answers

The repetitions(task:) method in the example uses a trailing closure syntax. The parameter type is () -> _____.

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

Match the code snippet with its description:

<pre><code class="language-swift">3.repetitions { print(&quot;Hello!&quot;) } ``` = Prints 'Hello!' three times. ```swift var someInt = 3 someInt.square() ``` = Squares the value of `someInt`, making it 9. </code></pre> Signup and view all the answers

What must structure and enumeration methods do to modify self or its properties when the methods are part of an extension?

<p>Mark the instance method as <code>mutating</code>. (D)</p> Signup and view all the answers

Extensions can be used to override existing methods in a class.

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

Given let number = 123456, what will number[2] return, based on the Int extension that retrieves the digit at a given index?

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

In the example provided, the Kind enumeration defines three cases: negative, _____, and positive.

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

Match the integer with the appropriate Kind case according to the provided extension:

<p>-5 = negative 0 = zero 10 = positive</p> Signup and view all the answers

What does the terminator: "" argument do in the printIntegerKinds(_:) function?

<p>Specifies that no character should be added at the end of the printed output. (A)</p> Signup and view all the answers

Extensions can add entirely new types to a Swift program.

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

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.

<pre><code class="language-swift">extension String { var isPalindrome: Bool { let cleaned = self.lowercased().filter { $0.isLetter || $0.isNumber } return cleaned == String(cleaned.reversed()) } } </code></pre> Signup and view all the answers

When extending a generic type to conditionally add functionality, you use a _____ clause to specify the conditions under which the extension applies.

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

Match each computed property added to the Double type with the correct formula:

<p>km = self * 1_000.0 cm = self / 100.0 mm = self / 1_000.0 ft = self / 3.28084</p> Signup and view all the answers

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?

<p>When the value type defines custom initializers as part of its original implementation. (C)</p> Signup and view all the answers

Adding a mutating method to an enum within an extension requires the same mutating keyword as within the original enum definition.

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

Explain the purpose of the Kind enumeration within the context of the Int extension example, and describe how it's used.

<p>The <code>Kind</code> enumeration represents whether an integer is negative, zero, or positive. It's used to categorize integers and provide a descriptive representation of their sign or value.</p> Signup and view all the answers

Extensions are similar to _____ in Objective-C, but unlike them, Swift extensions don’t have names.

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

Match each structure with its stored properties:

<p>struct Size = width, height struct Point = x, y struct Rect = origin, size</p> Signup and view all the answers

Which statement is true regarding the application of extensions for protocol conformance?

<p>Extensions allow a type to adopt a protocol and fulfill its requirements separately from the type's original declaration. (C)</p> Signup and view all the answers

It is possible to define a new deinitializer within an extension.

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

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.

<ol> <li>Create an extension for the <code>String</code> type.</li> <li>Define a subscript that takes an <code>Int</code> index.</li> <li>Implement error handling to return nil if the index is out of bounds. Otherwise, return the character at the specified index.</li> </ol> Signup and view all the answers

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.

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

Match the code with the functionality that the code creates:

<pre><code class="language-swift">extension Int { mutating func square() { self = self * self } } ``` = Squares the value of an integer when called ```swift extension Double { var km: Double { return self * 1_000.0 } } ``` = This enables conversion from kilometers to meters. </code></pre> Signup and view all the answers

Flashcards

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?

Extensions can add computed instance properties and computed type properties.

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?

Extensions can provide new convenience initializers, but not designated initializers or deinitializers.

Signup and view all the flashcards

Can extensions define nested types?

Extensions can define and use new nested types within existing types.

Signup and view all the flashcards

Can extensions add protocol conformance?

Extensions can make an existing type conform to a protocol.

Signup and view all the flashcards

How do you declare an extension?

Extensions are declared using the extension keyword.

Signup and view all the flashcards

How to conditionally extend a generic type?

You can extend a generic type to conditionally add functionality using a generic where clause.

Signup and view all the flashcards

Are computed properties added by extensions read-only?

Computed properties added by extensions are read-only and are defined without the get keyword for brevity.

Signup and view all the flashcards

How can you change an instance in an extension method?

Extensions can define instance methods that modify the instance itself, these methods must be marked as mutating.

Signup and view all the flashcards

Can extensions add subscripts?

Extensions can add new subscripts to an existing type.

Signup and view all the flashcards

Can extensions add nested enumerations?

Extensions can add new nested enumerations to existing types.

Signup and view all the flashcards

How can extensions return enumeration cases?

Extensions can add new computed properties that return a specific case of a nested enumeration.

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 returns self, interpreting a Double of 1.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 a Double 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.

Quiz Team

More Like This

Swift Programming Basics Tutorial
25 questions
Bootcamp Full Stack Swift 2024
40 questions
Introduction to Swift Programming
20 questions
Use Quizgecko on...
Browser
Browser