Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare a protocol named Drivable.
Swift
protocol [1] {
func drive()
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a noun like 'Driver' instead of a protocol name.
Misspelling the protocol name.
✗ Incorrect
The protocol name should be
Drivable to describe something that can be driven.2fill in blank
mediumComplete the code to make Car conform to the Drivable protocol.
Swift
struct Car: [1] { func drive() { print("Car is driving") } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong protocol name.
Forgetting the colon before the protocol name.
✗ Incorrect
To conform to a protocol, the type must list the protocol name after a colon.
3fill in blank
hardFix the error in the code by completing the function parameter type with the protocol name.
Swift
func startDriving(vehicle: [1]) {
vehicle.drive()
}
let myCar = Car()
startDriving(vehicle: myCar) Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the concrete type 'Car' instead of the protocol.
Misspelling the protocol name.
✗ Incorrect
Using the protocol as a type allows any conforming type to be passed in.
4fill in blank
hardFill both blanks to create a variable of protocol type and call its method.
Swift
var vehicle: [1] = Car() vehicle.[2]()
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the concrete type as variable type instead of the protocol.
Calling a method not declared in the protocol.
✗ Incorrect
The variable should be declared as the protocol type and call the protocol method.
5fill in blank
hardFill all three blanks to define a protocol, a conforming struct, and use the protocol as a type.
Swift
protocol [1] { func [2]() } struct Bike: [1] { func [2]() { print("Bike is moving") } } let myVehicle: [1] = Bike() myVehicle.[2]()
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names for protocol and method in different places.
Choosing method names not matching the protocol.
✗ Incorrect
The protocol is named Movable with method move. The struct conforms to Movable and implements move. The variable uses Movable type and calls move.