0
0
Swiftprogramming~10 mins

Protocol extensions with default implementations in Swift - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a protocol named Printable.

Swift
protocol [1] {
    func printDescription()
}
Drag options to blanks, or click blank then click option'
ADescribable
BPrintableProtocol
CPrintableExtension
DPrintable
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different protocol name than 'Printable'.
Forgetting the 'protocol' keyword.
2fill in blank
medium

Complete the code to add a default implementation for printDescription() in a protocol extension.

Swift
extension Printable {
    func [1]() {
        print("Default description")
    }
}
Drag options to blanks, or click blank then click option'
AshowDescription
Bdescribe
CprintDescription
Ddisplay
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different method name than the protocol requires.
Omitting the method implementation.
3fill in blank
hard

Fix the error in the struct that conforms to Printable but does not implement printDescription().

Swift
struct Document: Printable {
    var title: String

    func [1]() {
        print("Document title: \(title)")
    }
}
Drag options to blanks, or click blank then click option'
AprintDescription
Bdescribe
CshowTitle
DdisplayTitle
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different method name than the protocol requires.
Not implementing the required method or relying on a wrong name.
4fill in blank
hard

Fill both blanks to create a protocol extension that adds a new method and a default implementation.

Swift
extension Printable {
    func [1]() {
        print("Extra info")
    }

    func [2]() {
        print("Default description")
    }
}
Drag options to blanks, or click blank then click option'
AextraInfo
BprintDescription
CshowInfo
Ddescribe
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing method names or using names not matching the protocol.
Not providing default implementation for the protocol method.
5fill in blank
hard

Fill all three blanks to create a struct that uses the default implementation and calls the extra method.

Swift
struct Report: Printable {
    var name: String

    func [1]() {
        print("Report name: \(name)")
    }

    func show() {
        [2]()
        [3]()
    }
}
Drag options to blanks, or click blank then click option'
AprintDescription
BextraInfo
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong method names in the struct.
Not calling the methods correctly inside 'show()'.