0
0
Swiftprogramming~10 mins

Protocol composition in practice 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 variable that conforms to both protocols.

Swift
protocol Drivable {
    func drive()
}

protocol Flyable {
    func fly()
}

var vehicle: [1]
Drag options to blanks, or click blank then click option'
ADrivable | Flyable
BDrivable & Flyable
CDrivable, Flyable
DDrivable or Flyable
Attempts:
3 left
💡 Hint
Common Mistakes
Using | instead of & for protocol composition.
Separating protocols with commas or words like 'or'.
2fill in blank
medium

Complete the function parameter type to accept any object conforming to both protocols.

Swift
func operate(vehicle: [1]) {
    vehicle.drive()
    vehicle.fly()
}
Drag options to blanks, or click blank then click option'
ADrivable & Flyable
BDrivable, Flyable
CDrivable | Flyable
DDrivable or Flyable
Attempts:
3 left
💡 Hint
Common Mistakes
Using | instead of & in parameter types.
Using commas or words like 'or' instead of &.
3fill in blank
hard

Fix the error in the variable declaration to use protocol composition correctly.

Swift
var gadget: [1]
Drag options to blanks, or click blank then click option'
ADrivable, Flyable
BDrivable | Flyable
CDrivable & Flyable
DDrivable or Flyable
Attempts:
3 left
💡 Hint
Common Mistakes
Using | or commas instead of &.
Writing 'or' instead of &.
4fill in blank
hard

Fill both blanks to create a function that accepts an object conforming to two protocols and calls their methods.

Swift
func performAction(on item: [1]) {
    item.[2]()
}
Drag options to blanks, or click blank then click option'
ADrivable & Flyable
Bdrive
Cfly
Drun
Attempts:
3 left
💡 Hint
Common Mistakes
Calling a method not defined in the protocols.
Using incorrect protocol composition syntax.
5fill in blank
hard

Fill all three blanks to create a dictionary comprehension that maps names to objects conforming to two protocols, filtering by a condition.

Swift
let fleet = ["car": carObj, "plane": planeObj]
let activeFleet = fleet.filter { $0.value is [1] }
    .mapValues { $0 as! [2] }
    .filter { $0.value.[3]() }
Drag options to blanks, or click blank then click option'
ADrivable & Flyable
Cdrive
Dfly
Attempts:
3 left
💡 Hint
Common Mistakes
Using only one protocol instead of composition.
Calling a method not defined in the protocols.