BLACK FRIDAY: Save 50% on all my Swift books and bundles! >>

SOLVED: Day 13: Need help solving an error

Forums > 100 Days of SwiftUI

After working through Paul's explanation of a protocol (and after creating a new struct that implements the protocol he created at the beginning of the video), my playground threw me an error that I'm not sure how to fix. When I called the commute method while using the Bicycle() struct as an arguement, I get an error that states "Cannot convert value of type 'Bicycle' to expected argument type 'Car'."

How do I fix this error?

protocol Vehicle {
    func estimateTime(for distance: Int) -> Int
    func travel(distance: Int)
}

struct Car: Vehicle {

    func estimateTime(for distance: Int) -> Int {
        distance / 50
    }

    func travel(distance: Int) {
        print("I'm driving \(distance)km.")
    }

    func openSunroof() {
        print("It's a nice day.")
    }
}

// Creating a new struct to reexamine how the protocol works
struct Bicycle: Vehicle {
    func estimateTime(for distance: Int) -> Int {
        distance / 10
    }

    func travel(distance: Int) {
        print("I'm cycling \(distance)km.")
    }
}

func commute(distance: Int, using vehicle: Car) {
    if vehicle.estimateTime(for: distance) > 100 {
        print("That's too slow! I'll try a different vehicle.")
    } else {
        vehicle.travel(distance: distance)
    }
}

let car = Car()
commute(distance: 100, using: car)
// Error gets thrown when I use 'bike' below
let bike = Bicycle()
commute(distance: 10, using: bike)

3      

Your function expects to receive a type 'Car' in the call, but you pass it a type 'Bicycle'.

func commute(distance: Int, using vehicle: Car) {

You need to have the function expect the more generic type 'Vehicle' in the call, instead.

func commute(distance: Int, using vehicle: Vehicle) {

Both types 'Car' and 'Bicycle' are defined as and conform to the protocol 'Vehicle'.

4      

This was perfectly explained. Thank you! I'll work on going back over my code and doing the rubber ducky method to see where my errors are coming from.

3      

Save 50% in my WWDC sale.

SAVE 50% All our books and bundles are half price for Black Friday, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.