0
0
Swiftprogramming~10 mins

Protocol as types 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 Drivable.

Swift
protocol [1] {
    func drive()
}
Drag options to blanks, or click blank then click option'
ADriver
BDrivable
CDriveable
DDrive
Attempts:
3 left
💡 Hint
Common Mistakes
Using a noun like 'Driver' instead of a protocol name.
Misspelling the protocol name.
2fill in blank
medium

Complete 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'
ADrivable
BDriving
CDriver
DDrive
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong protocol name.
Forgetting the colon before the protocol name.
3fill in blank
hard

Fix 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'
ADriveable
BCar
CVehicle
DDrivable
Attempts:
3 left
💡 Hint
Common Mistakes
Using the concrete type 'Car' instead of the protocol.
Misspelling the protocol name.
4fill in blank
hard

Fill 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'
ADrivable
Bdrive
Cstart
DCar
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.
5fill in blank
hard

Fill 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'
AMovable
Bmove
Cdrive
DRunnable
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names for protocol and method in different places.
Choosing method names not matching the protocol.